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)) # False print(check_is_square(16)) # True print(check_is_square(32)) # False print(check_is_square(64)) # True
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 <typename T> std::vector<T> convolve(const std::vector<T>& f, const std::vector<T>& g) { if (f.size() < 1 || g.size() < 1) return {}; const auto outputSize = static_cast<int>(f.size() + g.size() - 1); std::vector<float> fg(outputSize, 0.0); for (int n = 0; n < outputSize; n++) for (int m = 0; m < static_cast<int>(g.size()); m++) if (n - m >= 0 && n - m <= static_cast<int>(outputSize - g.size())) fg[n] += f[n - m] * g[m]; return fg; } int main() { // In this example the input is a vector of 1s and the filter is a weighted // average filter. The result is the sliding average of input using four points. const auto input = std::vector<float>(5, 1.0f); const auto filter = std::vector<float>(4, 0.25f); const auto fg = convolve<float>(input, filter); for (const auto& elem : fg) std::cout << elem << std::endl; return 0; }
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 : Co-prime numbers do not require to be prime numbers. <b>Properties of Co-Prime Numbers</b> Some of the properties of co-prime numbers are as follows. <ul> <li>1 is co-prime with every number.</li> <li>Every prime number is co-prime to each other: As every prime number have only two factors 1 and the number itself, the only common factor of two prime numbers will be 1. For example, 2 and 3 are two prime numbers. Factors of 2 are 1, 2 and factors of 3 are 1, 3. The only common factor is 1 and hence is co-prime.</li> <li>Any two successive numbers/ integers are always co-prime: Take any consecutive number such as 2, 3 or 3, 4 or 5, 6 and so on; they have 1 as their HCF.</li> <li>The sum of any two co-prime numbers are always co-prime with their product: 2 and 3 are co-prime and have 5 as their sum (2+3) and 6 as the product (2×3). Hence, 5 and 6 are co-prime to each other.</li> </ul>
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", &c, &d); gcd = hcf(c, d); if (gcd == 1) printf("%d and %d are relatively prime or co prime numbers . \n", c, d); else printf("%d and %d are not relatively prime or co prime numbers . \n", c, d); return (0); }
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 j) { return gcd<int_type>(i, j) == 1; } int main() { long long i, j; cout << "Enter two numbers : "; scanf("%lld %lld", &i, &j); cout << isCoPrime(i, j) << endl; return 0; }
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() { while (a != b) { if (a > b) { a -= b; } else { b -= a; } } return a; } public bool check() { return gcd() == 1; } } class Program { static void Main(string[] args) { int num1 = 10, num2 = 5; coprime cp = new coprime_numbers.coprime(num1, num2); if (cp.check()) Console.WriteLine("coprime"); else Console.WriteLine("not coprime"); Console.ReadKey(); } } }
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) { Scanner in = new Scanner(new InputStreamReader(System.in)); System.out.println("Enter 2 numbers: "); int num1 = in.nextInt(); int num2 = in.nextInt(); if(gcd(num1, num2) == 1) System.out.println("The entered numbers are Co-Prime numbers"); else System.out.println("The entered numbers are not Co-Prime numbers"); in.close(); } }
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 { return gcd(b, a) == 1; } } rl.question( "Enter two values to find for relative prime or co prime: ", numbers => { let [a, b] = numbers.split(" ").filter(function(e) { return parseInt(e, 10); }); console.log(coPrime(a, b)); rl.close(); } );
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 {} and {} coprime? {}",a,b,co_prime(a,b) ) }
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"); scanf("%lu", &n); printf("\nThe number of digits is --> %d\n", countDigits(n)); return (0); }
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); return 0; }
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++; number /= 10; } return count; } static void Main(string[] args) { int number = 89922; Console.WriteLine("number {0} has {1} digits", number, digits(number)); Console.ReadKey(); } } }
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 } func main() { fmt.Printf("%d, number of digits is %d\n", 123, countDigits(123)) fmt.Printf("%d, number of digits is %d\n", 0, countDigits(0)) fmt.Printf("%d, number of digits is %d\n", 6523123, countDigits(6523123)) }
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(int n) { if (n == 0) return 1; int count = 0; while (n != 0) { count++; n /= 10; } return count; } }
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(countDigits(2)); // => 1 console.log(countDigits(12)); // => 2 console.log(countDigits(887)); // => 3
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_digits = 0 var integer = abs(n) while integer > 0 { integer = integer/10 num_digits += 1 } return num_digits }
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; } return result; } def main(args: Array[String]){ var n :Int = 13; //to test //print("Enter number:\n") //n = (Console.readLine).toInt; println("Trailing zeroes in " + n + "! : " + trailingZeroes(n)+'\n'); } }
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) { Scanner sc = new Scanner(System.in); System.out.print("Enter n >> "); int n = sc.nextInt(); System.out.println("Number of trailing zeroes in " + n + "! : " + trailingZeroes(n)); } }
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; for (var i = 5; n / i >= 1; i *= 5) { count += n / i; } return count; }
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); printf("Enter n value: "); scanf("%d", &n); result = DelannoyGenerator(m, n); printf("Delannoy Number of (%d,%d) is %d \n", m, n, result); return (0); }
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, m - 1); return d; } int main() { int m, n, result = 0; std::cout << "Provide the 'n' value: "; std::cin >> n; std::cout << std::endl; std::cout << "Provide the 'm' value: "; std::cin >> m; std::cout << std::endl; result = DelannoyGenerator(n, m); std::cout << "The delannoy number is: " << result << std::endl; }
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,sum); return(0); } long long int factorial(long long int n) { if(n==0 || n==1){ return 1; } else{ return(n*factorial(n-1)); } }
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; return b; } int x1, y1; int d = gcd (b % a, a, x1, y1); x = y1 - (b / a) * x1; y = x1; return d; } bool find_any_solution (int a, int b, int c, int & x0, int & y0, int & g) { g = gcd (abs(a), abs(b), x0, y0); if (c % g != 0) return false; x0 *= c / g; y0 *= c / g; if (a < 0) x0 *= -1; if (b < 0) y0 *= -1; return true; } void shift_solution(int & x, int & y, int a, int b, int cnt) { x += cnt * b; y -= cnt * a; } //this returns the number of solutions exist int find_all_solutions(int a, int b, int c, int minx, int maxx, int miny, int maxy) { if (!find_any_solution(a, b, c, x, y, g)) return 0; a /= g; b /= g; int sign_a = a > 0 ? +1 : -1; int sign_b = b > 0 ? +1 : -1; shift_solution(x, y, a, b, (minx - x) / b); if (x < minx) shift_solution(x, y, a, b, sign_b); if (x > maxx) return 0; int lx1 = x; shift_solution(x, y, a, b, (maxx - x) / b); if (x > maxx) shift_solution(x, y, a, b, -sign_b); int rx1 = x; shift_solution(x, y, a, b, -(miny - y) / a); if (y < miny) shift_solution(x, y, a, b, -sign_a); if (y > maxy) return 0; int lx2 = x; shift_solution(x, y, a, b, -(maxy - y) / a); if (y > maxy) shift_solution(x, y, a, b, sign_a); int rx2 = x; if (lx2 > rx2) std::swap(lx2, rx2); lx = std::max (lx1, lx2); rx = std::min (rx1, rx2); return (rx - lx) / abs(b) + 1; } int main() { using namespace std; int a, b, c, maxx, maxy, minx, miny; cin >> a >> b >> c >> minx >> maxx >> miny >> maxy; if (find_all_solutions(a, b, c, minx, maxx, miny, maxy) != 0) for (int i = lx; i <= rx; i += b) cout << i << "\t" << ( c - a * i ) / b << endl; }
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 = 0; y < s2 - 1; y++, i += 2) { matrix[i][j] = (matrix[i + 1][j - 1] - matrix[i - 1][j - 1]) / (matrix[i + (i2 - 1)][0] - matrix[i - (i2 - 1)][0]); } i = i2; } } public static void main(String[] args) { Double[] commonValues = {1.0, 2.0, 3.0, 4.0}; Double[] commonFunValues = {1.0, 8.0, 27.0, 64.0}; int length = commonValues.length; double[][] mas = new double[(2 * length) - 1][length + 1]; for (int i = 0, z = 0; i < length; i++, z += 2) { mas[z][0] = commonValues[i]; mas[z][1] = commonFunValues[i]; } divided_diff(mas, length); for (int q = 0; q < length * 2 - 1; q++) { System.out.println(Arrays.toString(mas[q])); } } }
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 ] # y[][] is used for divided difference table where y[][0] is used for input y[0][0] = 1.0 y[1][0] = 8.0 y[2][0] = 27.0 y[3][0] = 64.0 # calculating divided difference table y=dividedDiffTable(x, y, n) # displaying divided difference table L = [] for i in range(2*n - 1): A = [] for j in range(n): A.append(" ") L.append(A) for i in range(n): j = i count = 0 while j < 2*n-1: if count < n-i: L[j][i] = str(round(y[count][i],4)) count = count + 1 j = j + 2 for i in range(2*n-1): for j in range(n): print(L[i][j],end = " ") print("")
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(){ int n; scanf("%d", &n); printf("%d\n", eulerPhi(n)); return 0; }
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) { // If yes, then update n and result while (n % p == 0) n /= p; result -= result / p; } // If n has a prime factor greater than sqrt(n) // (There can be at-most one such prime factor) if (n > 1) result -= result / n; return result; } int main() { long long n; cout << "Enter the value of N\n"; cin >> n; for (long long i = 1; i <= n; i++) printf("phi(%lld) = %lld\n", i, phi(i)); return 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-1) / n; } return res; } public static void main(String[] args) { int[] testCases = { 1, // denegerate case 2, // prime 11, // prime 2*2, // power of prime 3*3*3, // power of prime 3*5, // product of distinct primes 2*2*3*3, // product of distinct primes 5*23, // product of distinct primes 5*5*23, // product of distinct primes }; int[] expectedResults = { 1, 1, 10, 2, 18, 8, 12, 88, 440, }; for (int idx = 0; idx < testCases.length; idx++) { System.out.println("phi(" + testCases[idx] + ") = " + phi(testCases[idx])); System.out.println("Expected: " + expectedResults[idx]); } } }
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) return result n = int(input()) for i in range(1, n + 1): ans = phi(i) print("phi(" + str(i) + ") = " + str(ans))
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) for (int j = i; j <= MAXN; j += i) { phi[j] /= i; phi[j] *= (i - 1); } } } int main() { ETF_sieve(); int n; cin >> n; cout << phi[n] << endl; return 0; }
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() # print(sieve[1]) # print(sieve[2]) # print(sieve[3]) # print(sieve[10]) # print(sieve[20]) # print(sieve[200]) # print(sieve[2000])
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() { int num, exp; cout << "Input Number and Its Exponent" << endl;; cin >> num >> exp; cout << power(num, exp) << endl; }
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, (exponent-1)/2) } } func main() { fmt.Println(fast_power(2,10)) //1024 fmt.Println(fast_power(2,11)) //2048 fmt.Println(fast_power(3,20)) //3486784401 fmt.Println(fast_power(10,5)) //10000000 var result bool = true m := map[int]int{ 3:10, 2:12, 4:20, 5:1, 6:0, 7:8, 31:3, 20:3}; for k, v := range m { result = result && (float64(fast_power(k,v)) == math.Pow(float64(k),float64(v))) } if result { fmt.Println("Tests ok!") } else { fmt.Println("Error!") } }
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 # Divide the power by 2 power = int(power / 2) # Multiply base to itself base = (base * base) % MOD return result base = int(input("Enter base :")) power = int(input("Enter power :")) print(fast_power(base, power))
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() { int num, exp; printf("Input Number \n"); scanf("%d", &num); printf("Input Exponent \n"); scanf("%d", &exp); printf("The result is %d \n", power(num, exp)); return (0); }
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; } public static void main(String[] args){ System.out.println(exponentBySquare(2,9)); } }
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 long base, exp, mod; cin >> base >> exp >> mod; cout << powmod(base, exp, mod) << endl; return 0; }
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-with-reduce 10))
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(calculateFactorial(7)) // 6227020800 fmt.Println(calculateFactorial(13)) }
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: " + factorial(n)); } private static BigInteger factorial(int n) { BigInteger ret = BigInteger.ONE; for (int i = 1; i <= n; ++i) { ret = ret.multiply(BigInteger.valueOf(i)); } return ret; } }
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() println("Factorial is: " + factorial(n)) } private fun factorial(n: Long): BigInteger { var result = BigInteger.ONE for (i in 1..n) { result = result.multiply(BigInteger.valueOf(i)) } return result } }
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 together and then multiply the result by 2, and there you have it, # a fast fun way to calculate factorial. from decimal import Decimal factorial = input("Please give a number to factor: ") factorial = int(factorial) sum = 1 halfF = factorial / 2 halfF = int(halfF + 1) m = ( [] ) # Here i use an array as a POC to display the results that will be used to calculate factorial for i in range(1, halfF): j = factorial - i s = j * i m.append(s) print(i, "*", j, "=", s) sum *= s sum *= 2 print(sum) print(m)
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: %lli\n", factorial(atoi(argv[1]))); } long long factorial(int n) { long long ans = 1; for (int i = 1; i <= n; i++) { ans *= i; } return 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: %lli\n", factorial(atoi(argv[1]))); } long long factorial(int n) { if (n == 0) { return (1); } return n * factorial(n - 1); }
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 << endl; return 0; }
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 ( arg ); w[i * 2 + 1] = sin ( arg ); } return; } /* FFT */ void FFT(double *x, double *y, int n, double w[]) { int m, i, j, k, nbits; double tempx, tempy; m = 0; i = n; while (i > 0) { i /= 2; m++; } m -= 1; /* bit reversal */ nbits = n >> 1; j = 0; for (i = 0 ; i < n - 1 ; i++) { if (i < j) { tempx = x[i]; tempy = y[i]; x[i] = x[j]; y[i] = y[j]; x[j] = tempx; y[j] = tempy; } k = nbits; while (k <= j) { j -= k; k >>= 1; } j += k; } /* butterfly operations */ int mj, term_i, stride_i, mi, j2, count2; double u1, u2, t1, t2; mj = 1; stride_i = n / ( 4 * mj ); for (k = 0 ; k < m ; k++) { mi = 2 * mj; term_i = n / mi; for (i = 0 ; i < term_i ; i++) { count2 = 0; for (j = i * mi ; count2 < mj ; j++ , count2++) { j %= ( n - 1 ); j2 = ( j + mj ); int temp = count2 * n / mi; u1 = w[temp * 2 + 0]; u2 = - w[temp * 2 + 1]; t1 = u1 * x[j2] - u2 * y[j2]; t2 = u1 * y[j2] + u2 * x[j2]; x[j2] = x[j] - t1; y[j2] = y[j] - t2; x[j] += t1; y[j] += t2; } } stride_i /= 2; mj *= 2; } return; } int main(int argc, char* argv[]) { int n, i; printf("Enter the size of the discrete points of signal\n"); scanf("%d", &n); printf("Enter the real parts for each of the %d elements\n", n); double* real = (double *) malloc (n * sizeof (double)); double* imag = (double *) malloc (n * sizeof (double)); double* w = (double *) malloc (n * sizeof (double)); for (i = 0 ; i < n ; i++) { scanf("%lf", &real[i]); } printf("Enter the imaginary parts for each of the %d elements\n", n); for (i = 0 ; i < n ; i++) { scanf("%lf", &imag[i]); } twiddle(n, w); FFT(real, imag, n, w); printf("The transformed signal is:\n"); for (i = 0 ; i < n ; i++) { printf("%.lf+%.2lfj, ", real[i], imag[i]); } printf("\n"); return (0); }
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 length must be power of 2"); } this.cos = new double[n / 2]; this.sin = new double[n / 2]; for (int i = 0; i < n / 2; i++) { this.cos[i] = Math.cos(-2 * Math.PI * i / n); this.sin[i] = Math.sin(-2 * Math.PI * i / n); } } public static void shiftFFT (float[] real, float[] img) { if (real == null || img == null) { throw new NullPointerException("Buffers can't be null"); } if (real.length != img.length) { throw new IllegalArgumentException("Different buffer size"); } int size = real.length; if (size % 2 != 0) { throw new IllegalArgumentException("Buffer size must be even"); } for (int i = 0; i < size / 2; i++) { float tempReal = real[i]; float tempImg = img[i]; real[i] = real[i + size / 2]; img[i] = img[i + size / 2]; real[i + size / 2] = tempReal; img[i + size / 2] = tempImg; } } public void fft (float[] x, float[] y) { int i, j, k, n1, n2, a; double c, s, t1, t2; // Bit-reverse j = 0; n2 = this.N / 2; for (i = 1; i < this.N - 1; i++) { n1 = n2; while (j >= n1) { j = j - n1; n1 = n1 / 2; } j = j + n1; if (i < j) { t1 = x[i]; x[i] = x[j]; x[j] = (float) t1; t1 = y[i]; y[i] = y[j]; y[j] = (float) t1; } } // FFT n1 = 0; n2 = 1; for (i = 0; i < this.M; i++) { n1 = n2; n2 = n2 + n2; a = 0; for (j = 0; j < n1; j++) { c = this.cos[a]; s = this.sin[a]; a += 1 << this.M - i - 1; for (k = j; k < this.N; k = k + n2) { t1 = c * x[k + n1] - s * y[k + n1]; t2 = s * x[k + n1] + c * y[k + n1]; x[k + n1] = (float) (x[k] - t1); y[k + n1] = (float) (y[k] - t2); x[k] = (float) (x[k] + t1); y[k] = (float) (y[k] + t2); } } } } }
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 square root much faster than could be done if calculated in the proper way. It has surprising levels of accuracy that is sufficient for graphical applications. #include <iostream> #include <cstdint> // Part of Cosmos by OpenGenus Foundation double fastInverseSqrt(double x) { float xhalf = 0.5f * x; std::int64_t i = *(std::int64_t*)&x; // get bits for double value i = 0x5fe6eb50c7b537a9 - (i >> 1); // gives initial guess y0 x = *(double*)&i; // convert bits back to double x = x * (1.5 - (xhalf * x * x)); // Newton step, repeating increases accuracy return x; } int main() { double input; std::cin >> input; std::cout << fastInverseSqrt(input) << std::endl; return 0; }
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 # predetermined magic value bit_result = format( (magic_number - bit_value), "032b" ) # subtracts magic number and bit value float_result = struct.unpack("!f", struct.pack("!I", int(bit_result, 2)))[ 0 ] # converts 32 bit result to float result precise_result = float_result * ( 1.5 - half * float_result * float_result ) # applies newton's method to get more precise value return precise_result print(fast_inverse_square_root(3.14)) # estimated value: 0.5640973663058647 actual value: 0.564332648
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; return sp % p; } ll stringToInt(string a, ll p) { ll ans = 0; for (size_t i = 0; i < a.length(); i++) ans = ((ans * 10) % p + a[i] - '0') % p; return ans; } int main() { ll n, m, p = 1000000007; ll t; cin >> t; string a, b; while (t--) // testcases { cin >> a >> b; n = stringToInt(a, p); m = stringToInt(b, p - 1); // using fermats theorem cout << power(n, m, p) << endl; } return 0; } /* * Sample Input: * * 5 * 3 2 * 4 5 * 7 4 * 34534985349875439875439875349875 93475349759384754395743975349573495 * 34543987529435983745230948023948 3498573497543987543985743989120393097595572309482304 * * ------------------------------------------------------------------------------ * * Output: * * 1024 * 2401 * 735851262 * 985546465: * */
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; } public static long stoi(String a, long mod) { long ans = 0; for (int i = 0; i < a.length(); i++) ans = ((ans * 10) % mod + a.charAt(i) - '0') % mod; return ans; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); long t, n, m, mod = 1000000007; t = sc.nextLong(); String a, b; while (t-- > 0) { a = sc.next(); b = sc.next(); n = stoi(a, mod); m = stoi(b, mod - 1); // Fermats theorem System.out.println(power(n, m, mod)); } } } /* Sample Input : 5 3 2 4 5 7 4 34534985349875439875439875349875 93475349759384754395743975349573495 34543987529435983745230948023948 3498573497543987543985743989120393097595572309482304 Sample Output : 9 1024 2401 735851262 985546465 */
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 in range(len(a)): a_mod_m = (a_mod_m * 10 % m + int(a[i]) % m) % m return a_mod_m def findPowerModuloP(args): cases = args.cases p = args.prime or 1000000007 for case in cases: a_str, b_str = case.split(",") a = stringToInt(a_str, p) b = stringToInt(b_str, p - 1) # using Fermats little theorem, (a^(p-1))%p = 1 pow_ab_mod_m = power(a, b, p) print("%s^%s modulo %d = %d" % (a_str, b_str, p, pow_ab_mod_m)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "cases", type=str, nargs="+", help="comma seperated values of a and b in a^b" ) parser.add_argument( "--prime", type=int, help="prime number aginst which to take the modulo (default: 1000000007)", ) args = parser.parse_args() findPowerModuloP(args) # Test # ---------- # python fermats_little.py 3,2 4,5 7,4 34534985349875439875439875349875,93475349759384754395743975349573495 34543987529435983745230948023948,3498573497543987543985743989120393097595572309482304 # output: # 3^2 modulo 1000000007 = 9 # 4^5 modulo 1000000007 = 1024 # 7^4 modulo 1000000007 = 2401 # 34534985349875439875439875349875^93475349759384754395743975349573495 modulo 1000000007 = 735851262 # 34543987529435983745230948023948^3498573497543987543985743989120393097595572309482304 modulo 1000000007 = 985546465
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; for (size_t j = 0; j < v.size(); j++) { if (v[j] < 10) continue; if (j == v.size() - 1) v.push_back(0); v[j + 1] += v[j] / 10; v[j] %= 10; } } for (auto it = v.rbegin(); it != v.rend(); it++) cout << *it; return 0; }
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): if n <= 0: return 0 f0, f1 = 0, 1 while n >= 2: f0, f1 = f1, f0 + f1 n -= 1 return f1 # Lucas's identities: # F(2k) = (2*F(k-1) + F(k)) * F(k) # F(2*k-1) = F(k) * F(k) + F(k-1) * F(k-1) def fib_lucas(n): if n <= 1: return n k = (n + 1) // 2 fk, fk_1 = fib_lucas(k), fib_lucas(k - 1) return fk * fk + fk_1 * fk_1 if n % 2 else (2 * fk_1 + fk) * fk def fib_lucas_mem(n): cache = {0: 0, 1: 1} def fib(n): if n in cache: return cache[n] k = (n + 1) // 2 fk, fk_1 = fib(k), fib(k - 1) fn = fk * fk + fk_1 * fk_1 if n % 2 else (2 * fk_1 + fk) * fk cache[n] = fn return fn return fib(n) # Measures the time for computing func(n) number times. def test_it(func, n, number=1): func_name = func.__name__ stmt = "{}({})".format(func_name, n) setup = "from __main__ import {}".format(func_name) print(func_name, timeit.timeit(stmt=stmt, setup=setup, number=number)) if __name__ == "__main__": n = 1000000 number = 1 res = set() for f in [fib_iter, fib_lucas, fib_lucas_mem]: test_it(f, n, number) res.add(f(n)) assert len(res) == 1 M = 1000 ** 3 + 7 print(res.pop() % M) # Example of the output: # fib_iter 10.709764141996857 # fib_lucas 0.49604503500449937 # fib_lucas_mem 0.047084556994377635 # 918091266
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) { memset(temp, 0, sizeof temp); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) temp[i][j] += (ret[i][k] * fib[k][j]); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) ret[i][j] = temp[i][j]; } memset(temp, 0, sizeof temp); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) temp[i][j] += (fib[i][k] * fib[k][j]); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) fib[i][j] = temp[i][j]; n /= 2; } return ret[0][1]; } int main() { //test case : Print 50th fibonacci number cout << fib(50); }
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], [1, 0]] power(F, n // 2) multiply(F, F) if n % 2 != 0: multiply(F, M) def multiply(F, M): """ Multiplies two matrix F, M Stores the result in F """ x = F[0][0] * M[0][0] + F[0][1] * M[1][0] y = F[0][0] * M[0][1] + F[0][1] * M[1][1] z = F[1][0] * M[0][0] + F[1][1] * M[1][0] w = F[1][0] * M[0][1] + F[1][1] * M[1][1] F[0][0] = x F[0][1] = y F[1][0] = z F[1][1] = w if __name__ == "__main__": # Test Case : Printing first 10 Fibonacci numbers for i in range(10): print(fibonacci(i))
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) + fib(n-1) return cache[n]! } return fib(n) } if let argument = Int(CommandLine.arguments[1]) { print(fibonnaci(n: argument)) print(fibonnaciMemoized(n: argument)) }
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 (+' (fibonacci-rec (- n 1)) (fibonacci-rec (- n 2))))) ;; prints 6765 (println (fibonacci 20)) (println (fibonacci-rec 20))
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_fibonacci(unsigned short n) { std::vector<unsigned long long> f(n + 1); f[0] = 0; f[1] = 1; for (int i = 2; i <= n; ++i) f[i] = f[i - 1] + f[i - 2]; return f[n]; } //Returns the nth term in the Fibonacci Sequence (recursive): O(2^N) [really slow] unsigned long long recursive_fibonacci(unsigned short n) { if (n == 0) return 0; if (n == 1) return 1; return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2); } int main() { unsigned short n = 45; std::cout << "Calculating fib(" << n << ") using bottom-up method: "; std::cout << bottom_up_fibonacci(n) << std::endl; std::cout << "Calculating fib(" << n << ") using recursive method: "; std::cout << recursive_fibonacci(n) << std::endl; // As you can see bottom-up it's instantanious but recursive takes some seconds to calculate fib. }
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.WriteLine(Fibonacci(42)); // 165580141 Console.WriteLine(Fibonacci(123)); // 14028366653498915298923761 Console.WriteLine(Fibonacci(777)); // 668226711200301698374224176558256700160458774333255425461900331623619273605518323137569702870357755802337031006361339094239227806499153841600804020665750176206357 Console.WriteLine(Fibonacci(1001)); // 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875 } static BigInteger Fibonacci(int n) { int i = 0; BigInteger a = 0, b = 1; while(++i < n) { b += a; a = b - a; } return a; } } }
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.Println(fibonacci(10)) fmt.Println(fibonacci(8)) fmt.Println(fibonacci(5)) fmt.Println(fibonacci(2)) }