filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/mathematical_algorithms/src/check_is_square/check_is_square_alternative.py
import math def check_is_square(input): return math.sqrt(input) == math.floor(math.sqrt(input)) if __name__ == "__main__": print(check_is_square(0)) # True print(check_is_square(1)) # True print(check_is_square(2)) # False print(check_is_square(4)) # True print(check_is_square(8)) # Fal...
code/mathematical_algorithms/src/collatz_conjecture_sequence/collatz_conjecture_sequence.c
#include <stdio.h> void collatz_conjecture_sequence(int n) { printf("%d ", n); while (n != 1) { if(n % 2 == 0) n = n / 2; else n = (3 * n) + 1; printf("%d ", n); } printf("\n"); } int main() { int n = 15; collatz_conjecture_sequence(n); return (0); }
code/mathematical_algorithms/src/convolution/convolution.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> // This code requires you to enable the C++11 standard when compiling /** * @breif convolve - compute the discrete time convolution of functions vectors f and g. Coded for clarity, * not performance. * @return f * g **/ template <t...
code/mathematical_algorithms/src/coprime_numbers/README.md
# Coprime_number Two numbers are said to be co-prime numbers if they do not have a common factor other than 1 or two numbers whose Highest Common Factor (HCF) or Greatest Common Divisor (GCD) is 1 are known as co-prime numbers. Examples of co-prime numbers are: 3 and 7 are co-prime, 7 and 10 are co-prime etc. Note ...
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.c
// Part of Cosmos by OpenGenus Foundation #include<stdio.h> int hcf(int a, int h) { int temp; while (1) { temp = a % h; if (temp == 0) return h; a = h; h = temp; } } int main() { int c, d, gcd; printf("Enter two Natural Numbers\n"); scanf("%d %d...
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; template<typename int_type> int_type gcd(int_type i, int_type j) { while (j != 0) { int_type x = i; i = j; j = x % j; } return i; } template<typename int_type> bool isCoPrime(int_type i, int_type...
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace coprime_numbers { class coprime { int a, b; public coprime(int num1,int num2) { a = num1; b = num2; } int gcd() ...
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.go
package main import "fmt" func gcd(a, b int) int { for b != 0 { a, b = b, a%b } return a } func coprime(a, b int) bool { return gcd(a, b) == 1 } func main() { a := 14 b := 15 fmt.Printf("Are %v and %v coprime? %v\n", a, b, coprime(a, b)) }
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.java
import java.io.InputStreamReader; import java.util.Scanner; class CoprimeNumbers { public static int gcd(int num1 , int num2) { int tmp = 1; while(tmp != 0) { tmp = num1 % num2; if(tmp == 0) return num2; num1 = num2; num2 = tmp; } return num2; } public static void main(String []args) { Sca...
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.js
const Readline = require("readline"); const rl = Readline.createInterface({ input: process.stdin, output: process.stdout }); function gcd(a, b) { while (b != 0) { let temp = a % b; a = b; b = temp; } return a; } function coPrime(a, b) { if (a > b) { return gcd(a, b) == 1; } else { ...
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.py
# Part of Cosmos by OpenGenus Foundation def gcd(a, b): while b != 0: a, b = b, a % b return a def coprime(a, b): return gcd(a, b) == 1 a, b = list(map(int, input().split())) print(coprime(a, b))
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.rb
def factor_finder(num) i = 1 fact = [] while i <= num fact << i if num.modulo(i) == 0 i += 1 end fact end def is_coprime?(num1, num2) f1 = factor_finder(num1) f2 = factor_finder(num2) common = f1 & f2 common.length == 1 end print is_coprime?(22, 21).to_s # output >> true
code/mathematical_algorithms/src/coprime_numbers/coprime_numbers.rs
fn gcd(mut a: i32, mut b: i32) -> i32 { while b != 0 { let temp = a % b; a = b; b = temp; } a } fn co_prime(a: i32, b: i32) -> bool { if a > b { gcd(a,b) == 1 }else { gcd(b,a) == 1 } } fn main() { let a = 15; let b = 14; println!("Are...
code/mathematical_algorithms/src/count_digits/count_digits.c
#include<stdio.h> // Part of Cosmos by OpenGenus Foundation // Code written by Adeen Shukla (adeen-s) int countDigits(unsigned long n) { if(n == 0) { return (1); } int count = 0; while(n != 0) { count++; n /= 10; } return (count); } int main() { unsigned long n; printf("\nEnter a number\n"); sca...
code/mathematical_algorithms/src/count_digits/count_digits.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation int count_digits(int n) { if (n == 0) return 1; int count = 0; while (n != 0) { count++; n /= 10; } return count; } int main() { int n; cin >> n; cout << count_digits(n); ...
code/mathematical_algorithms/src/count_digits/count_digits.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace count_digits { class Program { static int digits(int number) { int count = 0; while (number != 0) { count++; ...
code/mathematical_algorithms/src/count_digits/count_digits.go
// Part of Cosmos by OpenGenus Foundation package main /* Expected output 123, number of digits is 3 0, number of digits is 1 6523123, number of digits is 7 */ import "fmt" func countDigits(target int) int { if target == 0 { return 1 } count := 0 for target != 0 { target /= 10 count++ } return count ...
code/mathematical_algorithms/src/count_digits/count_digits.hs
countDigits :: Integer -> Integer countDigits 0 = 0 countDigits n = succ $ countDigits $ quot n 10
code/mathematical_algorithms/src/count_digits/count_digits.java
/* Part of Cosmos by OpenGenus Foundation */ public class CountDigits { public static void main(String args[]) { System.out.println(countDigits(0)); // => 1 System.out.println(countDigits(2)); // => 1 System.out.println(countDigits(337)); // => 3 } public static int countDigits...
code/mathematical_algorithms/src/count_digits/count_digits.js
// Part of Cosmos by OpenGenus Foundation function countDigits(n) { let numDigits = 0; let integers = Math.abs(n); if (n == 0) return 1; while (integers > 0) { integers = Math.floor(integers / 10); numDigits++; } return numDigits; } // Tests console.log(countDigits(0)); // => 1 console.log(count...
code/mathematical_algorithms/src/count_digits/count_digits.py
# Part of Cosmos by OpenGenus Foundation def count_digits(n): if n == 0: return 1 count = 0 while n != 0: count += 1 n //= 10 return count if __name__ == "__main__": number = input("Give me a number") print(count_digits(number))
code/mathematical_algorithms/src/count_digits/count_digits.swift
// // count_digits.swift // test // // Created by Kajornsak Peerapathananont on 10/14/2560 BE. // Copyright © 2560 Kajornsak Peerapathananont. All rights reserved. // // Part of Cosmos by OpenGenus Foundation import Foundation func count_digits(n : Int) -> Int { if n == 0 { return 1 } var num_d...
code/mathematical_algorithms/src/count_digits/counts_digits.rb
def count_num(num) count = 0 while num > 0 num /= 10 count += 1 end count end print count_num(2765).to_s
code/mathematical_algorithms/src/count_trailing_zeroes/count_trailing_zeroes.c
#include <stdio.h> // Part of Cosmos by OpenGenus Foundation int main() { int t; scanf("%d",&t); while(t--) { int num,x=5,count=0; scanf("%d",&num); while(x<=num) { count=count+(num/x); x=x*5; } printf("%d\n",count); } }
code/mathematical_algorithms/src/count_trailing_zeroes/count_trailing_zeroes.scala
//Part of Cosmos by OpenGenus Foundation object Count_trailing_zeroes { def trailingZeroes(n : Int) : Int = { var result :Int = 0; var i :Int = 5; while(i<n){ result += n/i; i*=5; } ...
code/mathematical_algorithms/src/count_trailing_zeroes/count_trailing_zeroes_factorial.cpp
#include <iostream> using namespace std; int findTrailingZeros(int n) { int count = 0; for (int i = 5; n / i >= 1; i *= 5) count += n / i; return count; } int main() { int n = 100; cout << "Count of trailing 0s in " << 100 << "! is " << findTrailingZeros(n); return 0; }
code/mathematical_algorithms/src/count_trailing_zeroes/count_trailing_zeroes_factorial.java
import java.util.Scanner; // Part of Cosmos by OpenGenus Foundation public class count_trailing_zeroes_factorial { public static int trailingZeroes(int n){ int count = 0; for(int i=5;n/i>=1;i*=5) count += n/i; return count; } public static void main(String[] args) { ...
code/mathematical_algorithms/src/count_trailing_zeroes/count_trailing_zeroes_factorial.js
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Enter the number: ", num => { console.log(`Number of trailing zeroes in ${num}! : ` + trailingZeroes(num)); rl.close(); }); function trailingZeroes(n) { var count = 0; ...
code/mathematical_algorithms/src/count_trailing_zeroes/count_trailing_zeroes_factorial.py
# Part of Cosmos by OpenGenus Foundation def findTrailingZeroes(n): count = 0 i = 5 while n // i >= 1: count = count + n // i i = i * 5 return count n = int(input("Enter the number:")) print("You entered " + str(n)) print("The number of trailing zeroes = " + str(findTrailingZeroes(n)))...
code/mathematical_algorithms/src/decoding_of_string/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/delannoy_number/README.md
# DelannoyNumbersGenerator A Delannoy number D describes the number of paths from the southwest corner (0, 0) of a rectangular grid to the northeast corner (m, n), using only single steps north, northeast, or east. More information about Delannoy number is available at: https://en.wikipedia.org/wiki/Delannoy_number
code/mathematical_algorithms/src/delannoy_number/delannoy_number.c
#include <stdio.h> int DelannoyGenerator(int m, int n) { int d = 1; if ((m == 0) || (n == 0)) d = 1; else d = DelannoyGenerator(m - 1, n) + DelannoyGenerator(m, n - 1) + DelannoyGenerator(m - 1, n - 1); return (d); } int main() { int m, n, result = 0; printf("Enter m value: "); scanf("%d", &m); pri...
code/mathematical_algorithms/src/delannoy_number/delannoy_number.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation int DelannoyGenerator(int n, int m) { int d = 1; if ((n == 0) || (m == 0)) d = 1; else d = DelannoyGenerator(n - 1, m) + DelannoyGenerator(n, m - 1) + DelannoyGenerator(n - 1, ...
code/mathematical_algorithms/src/delannoy_number/delannoy_number.py
def DelannoyGenerator(n,m): if n==0 or m==0: d = 1 else: d = DelannoyGenerator(n-1,m) + DelannoyGenerator(n,m-1) + DelannoyGenerator(n-1,m-1) return d n = int(input("Provide the 'n' value: ")) m = int(input("Provide the 'm' value: ")) print(f"The delannoy number is: {DelannoyGenerator(n,m)}")
code/mathematical_algorithms/src/derangements/derangements.c
#include <stdio.h> long long int factorial(long long int n); int main() { long long int n,sum=0; printf("Enter a Natural number\n"); scanf("%lli",&n); int sign=1; for(int i=2;i<=n;i++){ sum=sum+(sign*factorial(n)/factorial(i)); sign=-sign; } printf("Number of derangements possible for %lli are %lli\n",n,su...
code/mathematical_algorithms/src/dfa_division/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/diophantine/diophantine.cpp
#include <iostream> #include <vector> #include <algorithm> #include <cmath> // Part of Cosmos by OpenGenus Foundation // find all solution ax + by = c for (x, y) in range of [minx : maxx] and [miny : maxy] int x, y, g, lx, rx; int gcd (int a, int b, int & x, int & y) { if (a == 0) { x = 0; y = 1; ...
code/mathematical_algorithms/src/divided_differences/README.md
# cosmos > Your personal library of every algorithm and data structure code that you will ever encounter # Divided differences The second column is the value of the function. The first column - points. # Example 1 1 7 2 8 6 19 1 3 27 9 37 4 64
code/mathematical_algorithms/src/divided_differences/divided_differences.java
// Part of Cosmos by OpenGenus Foundation import java.util.Arrays; public class divided_differences { private static void divided_diff(double[][] matrix, int sLength) { int i = 1, i2 = 2, j = 2, s2 = sLength; for (int z = 0; z < sLength - 1; z++, j++, s2 -= 1, i2++) { for (int y =...
code/mathematical_algorithms/src/divided_differences/divided_differences.py
# Function for calculating divided difference table def dividedDiffTable(x, y, n): for i in range(1, n): for j in range(n - i): y[j][i] = ((y[j][i - 1] - y[j + 1][i - 1]) / (x[j] - x[i + j])) return y # number of inputs given n = 4 y = [[0 for i in range(10)] for j in range(10)] x = [ 1.0, 2.0, 3.0, 4.0 ] #...
code/mathematical_algorithms/src/euler_totient/README.md
Euler's totient function, also known as phi-function ϕ(n)ϕ(n), is the number of integers between 1 and n, inclusive, which are coprime to n. Two numbers are coprime if their greatest common divisor equals 1 use make to compile
code/mathematical_algorithms/src/euler_totient/euler_totient.c
#include <stdio.h> // Part of Cosmos by OpenGenus Foundation /* Time Complexity - O(sqrtN) */ int eulerPhi(int n){ int res = n; for(int i = 2; i*i <= n; i++){ if(n%i == 0){ while(n%i == 0){ n /= i; } res *= (i-1); res /= i; } } if(n != 1){ res *= (n-1); res /= n; } return res; } int main...
code/mathematical_algorithms/src/euler_totient/euler_totient.cpp
#include <iostream> using namespace std; long long phi(long long n) { long long result = n; // Initialize result as n // Consider all prime factors of n and subtract their // multiples from result for (long long p = 2; p * p <= n; ++p) // Check if p is a prime factor. if (n % p == 0) ...
code/mathematical_algorithms/src/euler_totient/euler_totient.java
/* Part of Cosmos by OpenGenus Foundation */ public class EulerTotient { public static int phi(int n) { if (n <= 0) return 0; int res = n; for (int i = 2; i * i <= n; i++){ if (n % i == 0){ do { n /= i; } while (n % i == 0); res -= res / i; } } if (n != 1) { res = res * (n-...
code/mathematical_algorithms/src/euler_totient/euler_totient.py
# Part of Cosmos by OpenGenus Foundation import math def phi(n): result = n for p in range(2, int(math.sqrt(n) + 1)): if n % p == 0: while n % p == 0: n = int(n / p) result = result - int(result / p) if n > 1: result = result - int(result / n) r...
code/mathematical_algorithms/src/euler_totient/euler_totient_sieve.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation const int MAXN = 1000000; int phi[MAXN + 1]; // calculates euler phi(n) for n <= MAXN void ETF_sieve() { for (int i = 1; i <= MAXN; i++) phi[i] = i; for (int i = 2; i <= MAXN; i++) { if (phi[i] == i) ...
code/mathematical_algorithms/src/euler_totient/euler_totient_sieve.py
# computes the sieve for the euler totient function def ETF_sieve(N=1000000): sieve = [i for i in range(N)] for i in range(2, N, 1): if sieve[i] == i: # this i would be a prime for j in range(i, N, i): sieve[j] *= 1 - 1 / i return sieve # #tests # sieve = ETF_sieve()...
code/mathematical_algorithms/src/exponentiation_power/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/exponentiation_power/exponentiation_by_squaring/exponentiation_by_squaring.c
#include <stdio.h> int power(int num, int exp) { if (exp == 0) return (1); if (exp == 1) return (num); int temp = power(num, exp / 2); temp *= temp; if (exp % 2 == 1 ) temp *= num; return (temp); }
code/mathematical_algorithms/src/exponentiation_power/exponentiation_by_squaring/exponentiation_by_squaring.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; int power(int num, int exp) { if (exp == 0) return 1; if (exp == 1) return num; int temp = power(num, exp / 2); temp *= temp; if (exp % 2 == 1) temp *= num; return temp; } int main() { ...
code/mathematical_algorithms/src/exponentiation_power/exponentiation_by_squaring/exponentiation_by_squaring.go
package main // Part of Cosmos by OpenGenus Foundation import ( "fmt" "math" ) func fast_power(base,exponent int) int { if exponent == 0 { return 1 } if exponent == 1 { return base } if exponent % 2 == 0 { return fast_power(base*base, exponent/2) } else { return base * fast_power(base*base, (exponen...
code/mathematical_algorithms/src/exponentiation_power/exponentiation_by_squaring/exponentiation_by_squaring.py
# Part of Cosmos by OpenGenus Foundation MOD = 1000000007 def fast_power(base, power): """ Returns the result of a^b i.e. a**b We assume that a >= 1 and b >= 0 """ result = 1 while power > 0: # If power is odd if power % 2 == 1: result = (result * base) % MOD ...
code/mathematical_algorithms/src/exponentiation_power/exponentiation_power.c
#include <stdio.h> // Part of Cosmos by OpenGenus Foundation int power(int num, int exp) { if (exp == 0) return (1); else if (exp == 1) return (num); int result = power(num, exp / 2); result *= result; if (exp % 2 == 1) result *= num; return (result); } int main()...
code/mathematical_algorithms/src/exponentiation_power/exponentiation_power.cpp
#include <ext/numeric> #include <iostream> using namespace std; using namespace __gnu_cxx; int main() { long long base, exp; cin >> base >> exp; cout << power(base, exp) << endl; return 0; }
code/mathematical_algorithms/src/exponentiation_power/exponentiation_power.java
class exponent{ public static int exponentBySquare(int num, int power){ if(power==0) return 1; if(power==1) return num; int temp=exponentBySquare(num,power/2); temp*=temp; if(power%2==1){ temp*=num; } return temp; }...
code/mathematical_algorithms/src/exponentiation_power/modulo_exponentation_power.cpp
#include <iostream> using namespace std; long long powmod(long long base, long long exp, long long mod) { long long ans = 1 % mod; while (exp > 0) { if (exp & 1) ans = (ans * base) % mod; base = (base * base) % mod; exp /= 2; } return ans; } int main() { long ...
code/mathematical_algorithms/src/factorial/factorial.c
#include<stdio.h> // function to find factorial of given number unsigned int factorial(unsigned int n) { if (n == 0) return (1); return (n * factorial(n - 1)); } int main() { int num = 5; printf("Factorial of %d is %d", num, factorial(num)); return (0); }
code/mathematical_algorithms/src/factorial/factorial.clj
;; Part of Cosmos by OpenGenus Foundation ;; with loop-recur (defn factorial [n] (loop [counter n acc 1] (if (zero? counter) acc (recur (dec counter) (*' acc counter))))) ;; with reduce (defn factorial-with-reduce [n] (reduce *' (range 1 (inc n)))) (println (factorial 10)) (println (factorial-wit...
code/mathematical_algorithms/src/factorial/factorial.erl
-module(factorial). -export([factorial/1]). factorial(0) -> 1; factorial(N) when N > 0 -> N * factorial(N - 1).
code/mathematical_algorithms/src/factorial/factorial.ex
defmodule Factorial do def factorial(0), do: 1 def factorial(n) when n > 0, do: n * factorial(n-1) end arg = String.to_integer(List.first(System.argv)) IO.puts Factorial.factorial(arg)
code/mathematical_algorithms/src/factorial/factorial.go
package main // Part of Cosmos by OpenGenus Foundation import ( "fmt" ) func calculateFactorial(i int) int { if i == 0 { return 1 } return i * calculateFactorial(i - 1) } func main() { // 120 fmt.Println(calculateFactorial(5)) // 6 fmt.Println(calculateFactorial(3)) // 5040 fmt.Println(calculateFactor...
code/mathematical_algorithms/src/factorial/factorial.hs
factorial n = product [1..n]
code/mathematical_algorithms/src/factorial/factorial.java
import java.util.Scanner; // Part of Cosmos by OpenGenus Foundation public class Factorial { public static void main(String args[]) { System.out.print("Enter a number: "); Scanner enterNum = new Scanner(System.in); int n = enterNum.nextInt(); System.out.println("Factorial is: " + fac...
code/mathematical_algorithms/src/factorial/factorial.kt
import java.math.BigInteger import java.util.* /** * Created by Phuwarin on 10/4/2018 * Part of Cosmos by OpenGenus */ object Factorial { @JvmStatic fun main(args: Array<String>) { print("Enter a number: ") val enterNum = Scanner(System.`in`) val n = enterNum.nextLong() pri...
code/mathematical_algorithms/src/factorial/factorial.php
<?php //recursive function to calculate factorial of a number // Part of Cosmos by OpenGenus Foundation function factorial($number) { if ($number < 2) { return 1; } else { return ($number * factorial($number-1)); } } ?>
code/mathematical_algorithms/src/factorial/factorial.rb
def factorial(n) if n == 0 1 else n * factorial(n - 1) end end input = ARGV[0].to_i puts factorial(input)
code/mathematical_algorithms/src/factorial/factorial.rs
use std::env; // Part of Cosmos by OpenGenus Foundation fn factorial(n: i64) -> i64 { if n == 0 { return 1; } else { return n * factorial(n-1); } } fn main() { if let Some(arg) = env::args().nth(1) { if let Ok(x) = arg.parse::<i64>() { println!("{}", factorial(x));...
code/mathematical_algorithms/src/factorial/factorial.scala
object Factorial extends App{ def factorial(n:Int):Long = { if(n == 0) return 1 else return n * factorial(n-1) } println(factorial(5)) }
code/mathematical_algorithms/src/factorial/factorial.swift
extension Int { func factorial() -> Int { guard self > 0 else { return 1 } return self * (self - 1).factorial() } } let x = -5 print(x.factorial()) print(0.factorial()) print(5.factorial())
code/mathematical_algorithms/src/factorial/factorial_hrw.py
#!/usr/local/bin/python3.6 # This is my way of calculating factorial, i call it the half reverse way, first you divide the number you want it's factorial # then you multiply every number until it's half counting up with every number until it's half counting down then # you multiply all of the multiplication results ...
code/mathematical_algorithms/src/factorial/factorial_iteration.c
#include <stdio.h> #include <stdlib.h> long long factorial(int n); int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: factorial_iteration n\n"); return (1); } if (atoi(argv[1]) == 0) { printf("Arg n most bigger then 0\n"); return (1); } printf("Ans: ...
code/mathematical_algorithms/src/factorial/factorial_iteration.cs
class factorial_iteration { public static int factorial(int n) { int product = 1; for(int i = 2 ; i <= n ; i++) product *= i; return product; } public static void Main() { System.Console.WriteLine(factorial(5)); } }
code/mathematical_algorithms/src/factorial/factorial_iteration.js
function factorial(n) { let ans = 1; for (let i = 1; i <= n; i += 1) { ans = ans * i; } return ans; } const num = 3; console.log(factorial(num));
code/mathematical_algorithms/src/factorial/factorial_iteration.py
# Part of Cosmos by OpenGenus Foundation def factorial_iteration(num): result = 1 while num != 0: result *= num num -= 1 return result n = int(input("Enter a number")) print("The factorial is ", factorial_iteration(n))
code/mathematical_algorithms/src/factorial/factorial_recursion.c
#include <stdio.h> #include <stdlib.h> long long factorial(int n); int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: factorial_iteration n\n"); return (1); } if (atoi(argv[1]) == 0) { printf("Arg n most bigger then 0\n"); return (1); } printf("Ans: ...
code/mathematical_algorithms/src/factorial/factorial_recursion.cpp
#include <iostream> // Part of Cosmos by OpenGenus Foundation using namespace std; long long int factorial(long long int n) { if (n == 0) return 1; else return n * factorial(n - 1); } int main() { long long int n; cin >> n; long long int result = factorial(n); cout << result ...
code/mathematical_algorithms/src/factorial/factorial_recursion.cs
class factorial_recursion { public static int factorial(int n) { if(n == 1) return 1; else return n * factorial(n - 1); } public static void Main() { System.Console.WriteLine(factorial(5)); } }
code/mathematical_algorithms/src/factorial/factorial_recursion.js
/* Part of Cosmos by OpenGenus Foundation */ function factorial(n) { return n === 0 ? 1 : n * factorial(n - 1); } const num = 3; console.log(factorial(num));
code/mathematical_algorithms/src/factorial/factorial_recursion.py
# Part of Cosmos by OpenGenus Foundation def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) n = int(input("Enter a number")) print("The factorial is " + str(factorial(n)))
code/mathematical_algorithms/src/fast_fourier_transform/fast_fourier_transform.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #define TAU 6.28318530718 /* look up table */ void twiddle(int n, double w[]) { double arg; double aw; int i; const double pi = TAU / 2; aw = 2.0 * pi / ((double ) n); for (i = 0 ; i < n / 2 ; i++) { arg = aw * ((double) i); w[i * 2 + 0] = cos ( ar...
code/mathematical_algorithms/src/fast_fourier_transform/fast_fourier_transform.java
public class FFT { private final double[] cos; private final double[] sin; private final int N; private final int M; public FFT(int n) { this.N = n; this.M = (int) (Math.log(n) / Math.log(2)); if (n != 1 << this.M) { throw new IllegalArgumentException("FFT leng...
code/mathematical_algorithms/src/fast_inverse_sqrt/fast_inverse_sqrt.cpp
// AUTHOR: Mitchell Haugen // GITHUB: https://github.com/haugenmitch // DATE: October 9, 2017 // SOURCE: https://stackoverflow.com/questions/1349542/john-carmacks-unusual-fast-inverse-square-root-quake-iii User: Rushyo // DESCRIPTION: This algorithm use bit manipulation to calculate the inverse sq...
code/mathematical_algorithms/src/fast_inverse_sqrt/fast_inverse_sqrt.py
import struct def fast_inverse_square_root(num): half = num / 2 # stores half of initial input unpacked_value = struct.unpack("!I", struct.pack("!f", num))[ 0 ] # unpacks input to get integer value from float bit_value = unpacked_value >> 1 # right bit shift magic_number = 0x5F3759DF ...
code/mathematical_algorithms/src/fermats_little_theorem/fermats_little_theorem.cpp
#include <iostream> #define ll long long int // Part of Cosmos by OpenGenus Foundation // Compute (A^B) mod (10^9+7) using namespace std; ll power(ll a, ll b, ll p) { if (b == 0) return 1; ll sp = power(a, b / 2, p); sp %= p; sp = (sp * sp) % p; if (b & 1) return (sp * a) % p; ...
code/mathematical_algorithms/src/fermats_little_theorem/fermats_little_theorem.java
import java.util.*; class Main { public static long power(long a, long b, long mod) { if (b == 0) return 1; long sp = power(a, b / 2, mod); sp %= mod; sp = (sp * sp) % mod; if ((b & 1) == 1) return (sp * a) % mod; return sp % mod; } ...
code/mathematical_algorithms/src/fermats_little_theorem/fermats_little_theorem.py
import sys import argparse # computes (a^b)%m # fermats little theorem is used assuming m is prime def power(a, b, m): if b == 0: return 1 p = power(a, b // 2, m) p = p % m p = (p * p) % m if b & 1: p = (p * a) % m return p def stringToInt(a, m): a_mod_m = 0 for i ...
code/mathematical_algorithms/src/fibonacci_number/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/mathematical_algorithms/src/fibonacci_number/fast_fibonacci.c
#include <stdio.h> typedef unsigned long long llu; llu Fibo(llu n)//finds nth Fibonacci term { return (llu)((pow((1+sqrt(5))/2,n)-pow((1-sqrt(5))/2,n))/sqrt(5)+0.5); }
code/mathematical_algorithms/src/fibonacci_number/fibonacci_for_big_numbers.cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n; cin >> n; vector<int > v; v.push_back(1); for (int i = 2; i <= n; i++) { for (auto it = v.begin(); it != v.end(); it++) *it *= i; ...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_lucas.py
# # Python-3 # # For running on Python-2, replace // with /. # # Many researchers found similar identities: # Vajda-11, Dunlap I7, Lucas(1878), # B&Q(2003) I13 and I14, # Hoggatt I11 and I10. # See http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormulae.html import timeit def fib_iter(n): ...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_matrix_exponentiation.cpp
#include <iostream> #include <cstring> using namespace std; long long fib(long long n) { long long fib[2][2] = {{1, 1}, {1, 0}}, ret[2][2] = {{1, 0}, {0, 1}}, temp[2][2] = {{0, 0}, {0, 0}}; int i, j, k; // Part of Cosmos by OpenGenus Foundation while (n > 0) { if (n & 1) { ...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_matrix_multiplication.py
def fibonacci(n): """ Returns the nth Fibonacci number F(0) = 0, F(1) = 1 .... """ if n == 0: return 0 F = [[1, 1], [1, 0]] power(F, n - 1) return F[0][0] def power(F, n): """ Transforms matrix F to F^n """ if n == 0 or n == 1: return M = [[1, 1],...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_memorized.swift
func fibonnaci(_ n: Int) -> Int { guard n > 1 else { return n } return fibonnaci(n-2) + fibonnaci(n-1) } func fibonnaciMemoized(_ n: Int) -> Int { var cache = [0: 0, 1: 1] func fib(_ n: Int) -> Int { if let number = cache[n] { return number } cache[n] = fib(n-2) + fi...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.c
#include <stdio.h> int main() { int n, num1 = 0, num2 = 1, temp; printf("How many Fibonacci numbers do you want?\n"); scanf("%d", &n); for (int i = 0; i <= n; i++) { printf("%d\n", num1); temp = num1 + num2; num1 = num2; num2 = temp; } return (0); }
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.clj
;; Part of Cosmos by OpenGenus Foundation ;; with loop-recur (defn fibonacci [n] (loop [cnt n prev 0 cur 1] (cond (= cnt 0) prev (= cnt 1) cur :else (recur (dec cnt) cur (+' prev cur))))) ;; with traditional recursion (defn fibonacci-rec [n] (cond (= n 0) 0 (= n 1) 1 :else (+' (f...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.cpp
#include <iostream> #include <vector> /* * Part of Cosmos by OpenGenus Foundation * Don't use numbers bigger than (2^16)-1 as input for fib because some computers will crash due to memory issues. */ // Returns the nth term in the Fibonacci Sequence (dynamic): O(N) [nice performance] unsigned long long bottom_up_fi...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.cs
using System; using System.Numerics; // Add this reference to the project to use BigInteger namespace FibonacciNumber { class Program { static void Main(string[] args) { Console.WriteLine(Fibonacci(1)); // 0 Console.WriteLine(Fibonacci(17)); // 987 Console.WriteLine(Fibonacci(33)); // 2178309 Console.Wr...
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.erl
-module(fibonacci). -export([fib/1]). fib(0) -> 0; fib(1) -> 1; fib(N) -> fib(N-1) + fib(N-2).
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.ex
defmodule Fib do def fib(0), do: 0 def fib(1), do: 1 def fib(n), do: fib(n-1) + fib(n-2) end arg = String.to_integer(List.first(System.argv)) IO.puts Fib.fib(arg)
code/mathematical_algorithms/src/fibonacci_number/fibonacci_number.go
package main // Part of Cosmos by OpenGenus Foundation import "fmt" //Returns the nth term in the Fibonacci Sequence func fibonacci(n int) int { if n <= 0 { return 0 } if n == 1 { return 1 } return fibonacci(n-1) + fibonacci(n-2) } //Fibonacci 30 and over can take a long time to compute. func main() { fmt....