filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/mathematical_algorithms/mathematical_algorithms/Solve_x_y/README.md
# Find (x, y) solutions for 1/x + 1/y=1/n ## Summary Find number of possible solution of 1/x + 1/y=1/n - Given n is a positive integer - x,y where x>=y and positive integer ## Solve - y is a smallest number integer among denominators - the smallest positive integer of y is y = n+1 - Therefore x = (n*y)/(y-n) ## Example Given a positive integer (n):5 - (x=30,y=6) solution for 1/5 = 1/30+1/6 - (x=10,y=10) solution for 1/5 = 1/10+1/10 ### Let solve to find all (x, y) solution in Python
code/mathematical_algorithms/mathematical_algorithms/automorphic_number.c
#include<stdio.h> int main(){ int n; printf("Enter the number\n"); scanf("%d",&n); int digit_count=0; for(int i=n;i>0;i/=10){ digit_count++; } int square_of_n=n*n; //digit extraction from behind in square int digits=0; int power=0; for(int i=square_of_n;i>0;i/=10){ if(power+1<=digit_count){ digits+=(i%10)*pow(10,power); power++; } } if(digits==n){ printf("\n%d is automorphic\n",n); } else{ printf("%d is not automorphic\n",n); } }
code/mathematical_algorithms/mathematical_algorithms/factorial/factorial.pl
# Part of Cosmos by OpenGenus Foundation $num = 6; $factorial = 1; for( $a = $num; $a > 0; $a = $a - 1 ) { $factorial = $factorial * $a; } print $factorial;
code/mathematical_algorithms/src/2sum/2sum.c
/* * Given an array and a sum, returns two numbers from the array that add-up to sum. * Part of Cosmos by OpenGenus Foundation. * Author : ABDOUS Kamel */ #include <stdio.h> #include <stdlib.h> int max(int a, int b) { if (a <= b) return (b); else return (a); } /* -------------------------------------- AVL TREE --------------------------------------------------- */ /* This code was taken from cosmos/code/data_structures/avl_tree/AVL_tree.cpp and adapted to work in C */ typedef struct AVLNode { int data; struct AVLNode* left; struct AVLNode* right; int height; } AVLNode; // helper function to return height of a node int getHeight(AVLNode* node) { if(node){ return node->height; } return -1; } // LL rotation rooted at X AVLNode* LL_rotation(AVLNode* X) { AVLNode* W = X->left; X->left = W->right; W->right = X; X->height = max(getHeight(X->left), getHeight(X->right)) + 1; W->height = max(getHeight(W->left), getHeight(X)) + 1; return W; //new root } // RR rotation rooted at X AVLNode* RR_rotation(AVLNode* X) { AVLNode* W = X->right; X->right = W->left; W->left = X; X->height = max(getHeight(X->left), getHeight(X->right)) + 1; W->height = max(getHeight(X), getHeight(W->right)); return W; //new root } // LR rotation rooted at X AVLNode* LR_rotation(AVLNode* X) { X->left = RR_rotation(X->left); return LL_rotation(X); } // RL rotation rooted at X AVLNode* RL_rotation(AVLNode* X) { X->right = LL_rotation(X->right); return RR_rotation(X); } int AVLFind(AVLNode* root, int data) { while(root != NULL) { if(root->data == data) return 1; else if(root->data < data) root = root->right; else root = root->left; } return 0; } // function to insert a node into the AVL tree AVLNode* insertIntoAVL(AVLNode* root, int data) { if(root == NULL) { AVLNode* newNode = (AVLNode*)(malloc(sizeof(*newNode))); newNode->data = data; newNode->height = 0; newNode->left = newNode->right = NULL; root = newNode; } else if(data < root->data) { root->left = insertIntoAVL(root->left, data); if(getHeight(root->left) - getHeight(root->right) == 2) { if(data < root->left->data) root = LL_rotation(root); else root = LR_rotation(root); } } else if(data > root->data) { root->right = insertIntoAVL(root->right, data); if(getHeight(root->right) - getHeight(root->left) == 2) { if(data > root->right->data) root = RR_rotation(root); else root = RL_rotation(root); } } root->height = max(getHeight(root->left), getHeight(root->right)) + 1; return root; } // function to free allocated memory void deleteTree(AVLNode *root) { if(root == NULL) return; deleteTree(root->left); deleteTree(root->right); free(root); } /* ----------------------------------------END OF AVL TREE ------------------------------------------------ */ int twoSum(int array[], int size, int sum, int* a, int* b) { int i; AVLNode* map = (AVLNode*)(malloc(sizeof(*map))); map->data = array[0]; map->height = 0; map->left = map->right = NULL; for (i = 1; i < size; ++i) { if (AVLFind(map, sum - array[i])) { *a = array[i]; *b = sum - array[i]; deleteTree(map); return (0); } else map = insertIntoAVL(map, array[i]); } deleteTree(map); return (-1); } int main() { int a[] = {1, 2, 3, 3, 5, 6}; int b, c; twoSum(a, 6, 9, &b, &c); printf("%d %d\n", b, c); return (0); }
code/mathematical_algorithms/src/2sum/2sum.cpp
//Given an array and a sum, print two numbers from the array that add-up to sum #include <iostream> #include <map> using namespace std; // Part of Cosmos by OpenGenus Foundation #define ll long long map<ll, ll> m; //Function to find two numbers which add up to sum void twoSum(ll a[], ll sum, int n) { for (int i = 0; i < n; i++) if (m[sum - a[i]]) { cout << "The two numbers are "; cout << a[i] << " " << sum - a[i] << endl; return; } } int main() { ll a[] = {1, 2, 3, 4, 5}; int n = sizeof(a) / sizeof(ll); ll sum = 8; for (int i = 0; i < n; i++) m[a[i]] = 1; twoSum(a, sum, n); return 0; }
code/mathematical_algorithms/src/2sum/2sum.go
package main import "fmt" // twoSum returns two numbers which add up to sum func twoSum(list []float64, sum float64) (a float64, b float64, hasResult bool) { n := len(list) m := make(map[float64]bool, 0) for i := 0; i < n; i++ { m[list[i]] = true } for i := 0; i < n; i++ { if m[sum-list[i]] { return list[i], sum - list[i], true } } return 0.0, 0.0, false } func main() { list := []float64{1, 2, 3, 4, 5} sum := 8.0 a, b, hasResult := twoSum(list, sum) if hasResult { fmt.Printf("Two numbers are (%f, %f).\n", a, b) } else { fmt.Println("There are no results.") } }
code/mathematical_algorithms/src/2sum/2sum.java
// Part of Cosmos by OpenGenus Foundation public class two_sum { private static int[] two_sum(int[] arr, int target) { if (arr == null || arr.length < 2) return new int[]{0, 0};//Condition to check HashMap<Integer, Integer> map = new HashMap<>();//Map Interface for (int i = 0; i < arr.length; i++) {//Loop total total length of array if (map.containsKey(arr[i])) {//Checking for a definite key return new int[]{map.get(arr[i]), i}; } else { map.put(target - arr[i], i); } } return new int[]{0, 0}; } //Driver's code public static void main(String[] args) {//Main method int[] arr1 = {3, 5, 7, 0, -3, -2, -3};//Initializing int[] arr2 = {3, 5, 0, -3, -2, -3};//Initializing System.out.println(Arrays.toString(two_sum(arr1, 4)));//Output condition System.out.println(Arrays.toString(two_sum(arr2, 4)));//Output condition } }
code/mathematical_algorithms/src/2sum/2sum.js
/*Part of cosmos by OpenGenus Foundation*/ function get2sum(a, b) { return a + b; } console.log(get2sum(2, 3));
code/mathematical_algorithms/src/2sum/2sum.py
# Part of Cosmos by OpenGenus Foundation # Given an array of integers, return the indices of the two numbers such that they add up to a specific target. def two_sum(array, target): indices = {} for i, n in enumerate(array): if target - n in indices: return (indices[target - n], i) indices[n] = i return (None, None) print(two_sum([3, 5, 7, 0, -3, -2, -3], 4)) print(two_sum([3, 5, 0, -3, -2, -3], 4))
code/mathematical_algorithms/src/2sum/2sum.rb
# Part of Cosmos by OpenGenus Foundation # Given an array of integers, return the indices of the two numbers such that they add up to a specific target. def two_sum(list, target) buffer = {} list.each_with_index do |val, idx| return [buffer[target - val], idx] if buffer.key?(target - val) buffer[val] = idx end [nil, nil] end p two_sum([3, 5, 7, 0, -3, -2, -3], 4) p two_sum([3, 5, 0, -3, -2, -3], 4)
code/mathematical_algorithms/src/2sum/2sum.rs
use std::collections::HashMap; // Part of Cosmos by OpenGenus Foundation fn main() { // 2 results - for `7` and both `-3` numbers two_sum(vec![3, 5, 7, 0, -3, -2, -3], 4); // No results two_sum(vec![3, 5, 0, -3, -2, -3], 4); } fn two_sum(numbers: Vec<i32>, target: i32) { let mut indices: HashMap<i32, usize> = HashMap::new(); println!("Numbers: {:?}", numbers); for (i, number) in numbers.iter().enumerate() { let hash_index = target - number; if indices.get(&hash_index).is_some() { println!("Found two indices that sum-up to {}: {} and {}", target, indices.get(&hash_index).unwrap(), i); } indices.insert(*number, i); } }
code/mathematical_algorithms/src/Binary_GCD_Algorithm/Binary_GCD_Iterative.cpp
// Iterative Approach #include <bits/stdc++.h> using namespace std; //GCD Function int gcd(int x, int y) { if (x == 0) return y; if (y == 0) return x; /*Finding K, where K is the greatest power of 2 that divides both a and b. */ int k; for (k = 0; ((x | y) && 1) == 0; ++k) { x >>= 1; y >>= 1; } /* Dividing x by 2 until x becomes odd */ while ((x > 1) == 0) x >>= 1; /* From here on, 'x' is always odd. */ do { /* If y is even, remove all factor of 2 in y */ while ((y > 1) == 0) y >>= 1; // Now x and y are both odd if (x > y) swap(x, y); // Swap u and v. x = (y - a); } while (y != 0); return x << k; } // Driver code int main() { int x = 72, b = 12; cout<<"Gcd of given numbers is "<< gcd(x, y)); return 0; }
code/mathematical_algorithms/src/Binary_GCD_Algorithm/Binary_GCD_Recursive.cpp
// Recursive program #include <bits/stdc++.h> using namespace std; // Function to implement the // Stein's Algorithm int gcd(int x, int y) { if (x == y) return x; if (x == 0) return y; if (y == 0) return x; // look for factors of 2 if (~x & 1) // x is even { if (y & 1) // y is odd return gcd(x >> 1, y); else // both x and y are even return gcd(x >> 1, y >> 1) << 1; } if (~y & 1) // x is odd, y is even return gcd(x, y >> 1); // reduce larger number if (x > y) return gcd((x - y) >> 1, y); return gcd((y - x) >> 1, x); } // Driver code int main() { int a = 34, b = 17; cout<<"Gcd of given numbers is"<<gcd(a, b)); return 0; }
code/mathematical_algorithms/src/Binary_GCD_Algorithm/Binary_GCD_Recursive.py
def gcd(a, b): if (a == b): return a if (a == 0): return b if (b == 0): return a if ((~a & 1) == 1): if ((b & 1) == 1): return gcd(a >> 1, b) else: return (gcd(a >> 1, b >> 1) << 1) if ((~b & 1) == 1): return gcd(a, b >> 1) if (a > b): return gcd((a - b) >> 1, b) return gcd((b - a) >> 1, a) a, b = 34, 17 print("Gcd of given numbers is ", gcd(a, b))
code/mathematical_algorithms/src/Binary_GCD_Algorithm/README.md
This article at Opengenus on Binary GCD Algorithm or Stien's Algorithm gives an entire overview of the algorithm, along with the following : * Background/Mathematical Concept related to the algorithm * PseudoCode * Detailed Example Explanation * Implementation * Complexity * Efficiency * Applications This algorithm is basically a variation of the standard GCD algorithm and uses arithmetic shifts and operations instead of the conventional multiplication and division operations. [Read the article to find out more interesting facts related to this algorithm](https://iq.opengenus.org/binary-gcd-algorithm/)
code/mathematical_algorithms/src/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/add_polynomials/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/add_polynomials/add_polynomials.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> #include <stdlib.h> /* * Node structure containing power and coefficient of variable. */ struct Node { int coeff; int pow; struct Node *next; }; /* * Function to create new node. */ void create_node(int x, int y, struct Node **temp) { struct Node *r, *z; z = *temp; if (z == NULL) { r = (struct Node*)malloc(sizeof(struct Node)); r->coeff = x; r->pow = y; *temp = r; r->next = (struct Node*)malloc(sizeof(struct Node)); r = r->next; r->next = NULL; } else { r->coeff = x; r->pow = y; r->next = (struct Node*)malloc(sizeof(struct Node)); r = r->next; r->next = NULL; } } /* * Function Adding two polynomial numbers */ void polyadd(struct Node *poly1, struct Node *poly2, struct Node *poly) { while (poly1->next && poly2->next) { /* If power of 1st polynomial is greater then 2nd, then store 1st as it is and move its pointer. */ if (poly1->pow > poly2->pow) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } /* If power of 2nd polynomial is greater then 1st, then store 2nd as it is and move its pointer */ else if (poly1->pow < poly2->pow) { poly->pow = poly2->pow; poly->coeff = poly2->coeff; poly2 = poly2->next; } /* If power of both polynomial numbers is same then add their coefficients. */ else { poly->pow = poly1->pow; poly->coeff = poly1->coeff+poly2->coeff; poly1 = poly1->next; poly2 = poly2->next; } /* Dynamically create new node */ poly->next = (struct Node *)malloc(sizeof(struct Node)); poly = poly->next; poly->next = NULL; } while (poly1->next || poly2->next) { if (poly1->next) { poly->pow = poly1->pow; poly->coeff = poly1->coeff; poly1 = poly1->next; } if (poly2->next) { poly->pow = poly2->pow; poly->coeff = poly2->coeff; poly2 = poly2->next; } poly->next = (struct Node *)malloc(sizeof(struct Node)); poly = poly->next; poly->next = NULL; } } /* Display Linked list. */ void show(struct Node *node) { while (node->next != NULL) { printf("%dx^%d", node->coeff, node->pow); node = node->next; if (node->next != NULL) printf(" + "); } } /* Driver program. */ int main() { struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL; /* Create first list of 5x^2 + 4x^1 + 2x^0 */ create_node(5,2,&poly1); create_node(4,1,&poly1); create_node(2,0,&poly1); /* Create second list of 5x^1 + 5x^0 */ create_node(5,1,&poly2); create_node(5,0,&poly2); printf("1st Number: "); show(poly1); printf("\n2nd Number: "); show(poly2); poly = (struct Node *)malloc(sizeof(struct Node)); /* Function add two polynomial numbers */ polyadd(poly1, poly2, poly); /* Display resultant List */ printf("\nAdded polynomial: "); show(poly); return (0); }
code/mathematical_algorithms/src/add_polynomials/add_polynomials.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* Contributed by Vaibhav Jain (vaibhav29498) */ /* Refactored by Adeen Shukla (adeen-s) */ #include <iostream> #include <stddef.h> using namespace std; struct term { int coeff; int pow; term* next; term(int, int); }; term::term(int c, int p) { coeff = c; pow = p; next = NULL; } class polynomial { term* head; public: polynomial(); void insert_term(int, int); void print(); friend polynomial operator+(polynomial, polynomial); }; polynomial::polynomial() { head = NULL; } void polynomial::insert_term(int c, int p) { if (head == NULL) { head = new term(c, p); return; } if (p > head->pow) { term* t = new term(c, p); t->next = head; head = t; return; } term* cur = head; while (cur != NULL) { if (cur->pow == p) { cur->coeff += c; return; } if ((cur->next == NULL) || (cur->next->pow < p)) { term* t = new term(c, p); t->next = cur->next; cur->next = t; return; } cur = cur->next; } } void polynomial::print() { term* t = head; while (t != NULL) { cout << t->coeff; if (t->pow) cout << "x^" << t->pow; if (t->next != NULL) cout << "+"; t = t->next; } cout << endl; } polynomial operator+(polynomial p1, polynomial p2) { polynomial p; term *t1 = p1.head, *t2 = p2.head; while ((t1 != NULL) && (t2 != NULL)) { if (t1->pow > t2->pow) { p.insert_term(t1->coeff, t1->pow); t1 = t1->next; } else if (t1->pow < t2->pow) { p.insert_term(t2->coeff, t2->pow); t2 = t2->next; } else { p.insert_term(t1->coeff + t2->coeff, t1->pow); t1 = t1->next; t2 = t2->next; } } while (t1 != NULL) { p.insert_term(t1->coeff, t1->pow); t1 = t1->next; } while (t2 != NULL) { p.insert_term(t2->coeff, t2->pow); t2 = t2->next; } return p; } int main() { polynomial p1, p2; p1.insert_term(7, 4); p1.insert_term(4, 5); p1.insert_term(10, 0); p1.insert_term(9, 2); cout << "First polynomial:"; p1.print(); p2.insert_term(5, 0); p2.insert_term(6, 5); p2.insert_term(7, 0); p2.insert_term(3, 2); cout << "Second polynomial:"; p2.print(); polynomial p3 = p1 + p2; cout << "Sum:"; p3.print(); return 0; }
code/mathematical_algorithms/src/add_polynomials/add_polynomials.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" type PolyNode struct { Coeff int Pow int } type polynomial struct { Data []PolyNode } func (p *polynomial) AddNode(coeff, pow int) { //Find a sutible location. index := -1 for i, data := range p.Data { if pow > data.Pow { index = i break } } if index == -1 { p.Data = append(p.Data, PolyNode{Coeff: coeff, Pow: pow}) } else { res := append([]PolyNode{}, p.Data[index:]...) p.Data = append(p.Data[:index], PolyNode{Coeff: coeff, Pow: pow}) p.Data = append(p.Data, res...) } } func (p *polynomial) Show() { for i, data := range p.Data { if i != 0 { fmt.Printf(" + ") } fmt.Printf("%dx^%d", data.Coeff, data.Pow) } fmt.Printf("\n") } func (p *polynomial) Length() int { return len(p.Data) } func (p *polynomial) GetNode(index int) PolyNode { return p.Data[index] } func Addpolynomial(p1, p2 polynomial) polynomial { ans := polynomial{} i, j := 0, 0 for i, j = 0, 0; i < p1.Length() && j < p2.Length(); { p1N := p1.GetNode(i) p2N := p2.GetNode(j) coeff := 0 pow := 0 if p1N.Pow == p2N.Pow { pow = p1N.Pow coeff = p1N.Coeff + p2N.Coeff i++ j++ } else if p1N.Pow > p2N.Pow { pow = p1N.Pow coeff = p1N.Coeff i++ } else { pow = p2N.Pow coeff = p2N.Coeff j++ } ans.AddNode(coeff, pow) } for ; i < p1.Length(); i++ { pN := p1.GetNode(i) ans.AddNode(pN.Coeff, pN.Pow) } for ; j < p2.Length(); j++ { pN := p2.GetNode(j) ans.AddNode(pN.Coeff, pN.Pow) } return ans } func main() { p1 := polynomial{} p2 := polynomial{} p1.AddNode(2, 11) p1.AddNode(2, 5) p1.AddNode(12, 4) p1.AddNode(3, 1) p1.AddNode(8, 2) fmt.Printf("polynomial one is ") p1.Show() p2.AddNode(1, 7) p2.AddNode(-4, 6) p2.AddNode(3, 4) p2.AddNode(4, 2) p2.AddNode(8, 0) fmt.Printf("polynomial two is ") p2.Show() ans := Addpolynomial(p1, p2) fmt.Printf("The sum of above two polynomial is ") ans.Show() }
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.c
#include <stdio.h> int main() { printf("Amicable Numbers below 10000 are:- \n"); int m, i, j; for (m = 1; m <= 10000; m++) { int x = m; int sum1 = 0, sum2 = 0; for (i = 1; i < x; i++) if (x % i == 0) sum1 += i; int y = sum1; for (j = 1; j < y; j++) if (y % j == 0) sum2 += j; if (sum2 == x && x != y) printf("%d \n", x); } return (0); }
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.cpp
// Part of Cosmos by OpenGenus Foundation //Program to Calculate Amicable Numbers under 10000 and find sum of them #include <iostream> using namespace std; int main() { int n, k; int i = 1, s1 = 0, s2 = 0, sum = 0; for (k = 1; k <= 10000; k++) { n = k; while (i < n) { if (n % i == 0) s1 = s1 + i; i++; } i = 1; if (s1 == n) continue; while (i < s1) { if (s1 % i == 0) s2 = s2 + i; i++; } if (n == s2) { cout << n << endl; sum += n; } s1 = 0; s2 = 0; } cout << "\nSum of Amicable numbers under 10000 is : " << sum; }
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace amicable_numbers { class Program { static void amicable_numbers(int from, int to) { for(int i = from; i < to; i++) { int x = i, y; int sum1 = 0, sum2 = 0; for (int j = 1; j < x; j++) { if (x % j == 0) sum1 += j; } y = sum1; for (int j = 1; j < y; j++) { if (y % j == 0) sum2 += j; } if (sum2 == x && x != y) { Console.WriteLine(x); } } } static void Main(string[] args) { int num1 = 10; int num2 = 2000; Console.WriteLine("amicable nunmbers between {0} and {1} are", num1, num2); amicable_numbers(num1, num2); Console.ReadKey(); } } }
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.go
package main import ( "fmt" ) // Get all prime factors of a given number n func PrimeFactors(n int) (pfs []int) { // Get the number of 2s that divide n for n%2 == 0 { pfs = append(pfs, 2) n = n / 2 } // n must be odd at this point. so we can skip one element // (note i = i + 2) for i := 3; i*i <= n; i = i + 2 { // while i divides n, append i and divide n for n%i == 0 { pfs = append(pfs, i) n = n / i } } // This condition is to handle the case when n is a prime number // greater than 2 if n > 2 { pfs = append(pfs, n) } return } // return p^i func Power(p, i int) int { result := 1 for j := 0; j < i; j++ { result *= p } return result } // formula comes from https://math.stackexchange.com/a/22723 func SumOfProperDivisors(n int) int { pfs := PrimeFactors(n) // key: prime // value: prime exponents m := make(map[int]int) for _, prime := range pfs { _, ok := m[prime] if ok { m[prime] += 1 } else { m[prime] = 1 } } sumOfAllFactors := 1 for prime, exponents := range m { sumOfAllFactors *= (Power(prime, exponents+1) - 1) / (prime - 1) } return sumOfAllFactors - n } func AmicableNumbersUnder10000() (amicables []int) { for i := 3; i < 10000; i++ { s := SumOfProperDivisors(i) if s == i { continue } if SumOfProperDivisors(s) == i { amicables = append(amicables, i) } } return } func main() { amicables := AmicableNumbersUnder10000() fmt.Println(amicables) sum := 0 for i := 0; i < len(amicables); i++ { sum += amicables[i] } fmt.Println(sum) }
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.java
import java.util.Set; import java.util.TreeSet; public class Amicable_numbers { public static void main(String[] args) { System.out.println("The sum of amicable numbers less than 1000 is " + getAmicableSum(10000)); } // returns the sum of all divisors less than n public static int getDivisorSum(int n) { Set<Integer> divisors = new TreeSet<Integer>(); int root = (int) Math.ceil(Math.sqrt(n)); for (int i = 1; i < root + 1; i++) { if ((double) n % i == 0 && i < n) { divisors.add(i); if (n / i < n) { divisors.add(n / i); } } } int divisorSum = 0; for (int i : divisors) { divisorSum += i; } return divisorSum; } // returns the sum of all amicable numbers less than max private static int getAmicableSum(int max) { int sum = 0; for (int i = 1; i < max; i++) { int a = getDivisorSum(i); int b = getDivisorSum(a); if (i == b && a != b) { sum += i; } } return sum; } }
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.js
function check(a, b) { let sum = 0; for (let i = 1; i < a; i++) { if (a % i == 0) { sum += i; } } if (sum == b) { return true; } } function ami_check(a, b) { if (check(a, b)) { if (check(b, a)) { console.log("Numbers are Amicable"); } else { console.log("Numbers are not Amicable"); } } else { console.log("Numbers are not Amicable"); } } ami_check(17296, 18416);
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.py
def ami_check(x, y): if x == y: return False # 1 sum_x = sum(e for e in range(1, x // 2 + 1) if x % e == 0) # 2 sum_y = sum(e for e in range(1, y // 2 + 1) if y % e == 0) # 2 return sum_x == y and sum_y == x # 3 if __name__ == "__main__": print(ami_check(220, 284))
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.rb
def sum_of_proper_divisors(num) (1..(num / 2)).select { |i| num % i == 0 }.inject(:+) end def ami_check(num1, num2) if num1 == num2 false else sum_of_proper_divisors(num1) == num2 && sum_of_proper_divisors(num2) == num1 end end puts ami_check(66_928, 66_992)
code/mathematical_algorithms/src/amicable_numbers/amicable_numbers.rs
fn sum_of_divisors(a: u64) -> u64 { let mut sum = 0; // let max = (a as f64).sqrt() as u64; // TODO: Optimize by checking up to sqrt of a and using iterators for i in 1..a { if a % i == 0 { sum += i; } } sum } fn is_amicable(a: u64, b: u64) -> bool { sum_of_divisors(a) == b && sum_of_divisors(b) == a } #[test] fn test_amicable() { assert!(!is_amicable(23, 234)); assert!(is_amicable(220, 284)); assert!(is_amicable(1184, 1210)); assert!(is_amicable(17296, 18416)); }
code/mathematical_algorithms/src/armstrong_num_range/README.md
# Finding all armstrong numbers in a given range ## [Article for finding all armstrong numbers in a given range](https://iq.opengenus.org/find-all-armstrong-numbers-in-a-range/) Armstrong Number, also known as Narcissistic Number in a given number base is a number that is the sum of its own digits, each raised to the power of the number of digits. This article covers various topics such as : * What is an Armstrong Number? * How to find calculate Armstrong Number? * Checking if an number is an Armstrong Number * ALgorithm for finding Armstrong Numbers in a given range * Implementation in Python and C * Complexity * Applications This article will give you the knowledge of how to find out the armstrong numbers in a given range.
code/mathematical_algorithms/src/armstrong_num_range/amstrong_num_range.c
#include <math.h> #include <stdio.h> int main() { int lower, upper, i, temp1, temp2, rem, num = 0; float sum_pow = 0.0; /* Accept the lower and upper range from the user */ printf("Enter lower range: "); scanf("%d", &lower); printf("Enter upper range: "); scanf("%d", &upper); printf("Armstrong numbers between %d and %d are: ", lower, upper); for (i = lower ; i <= upper; ++i) { temp1 = i; temp2 = i; // calculate number of digits while (temp1 != 0) { temp1 /= 10; ++num; } // calculate sum of nth power of its digits while (temp2 != 0) { rem = temp2 % 10; sum_pow += pow(rem, num); temp2 /= 10; } // check if it is an Armstrong number if ((int)sum_pow == i) { printf("%d ", i); } num = 0; sum_pow = 0; } return 0; }
code/mathematical_algorithms/src/armstrong_num_range/amstrong_num_range.py
sum_pow = 0.0 #Accept the lower and upper range from the user lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) print(f"Armstrong numbers between {lower} and {upper} are: ") for i in range(lower,upper+1): temp1 = i temp2 = i #calculate number of digits num = len(str(temp1)) #calculate sum of nth power of its digits while temp2 != 0: rem = int(temp2 % 10) sum_pow = sum_pow + pow(rem,num) temp2 = int(temp2 / 10) #check if it is an Armstrong number if int(sum_pow) == i: print(i) sum_pow = 0.0
code/mathematical_algorithms/src/armstrong_numbers/README.md
# Armstrong Number An Armstrong Number is a number of three digits, such that the sum of the cubes of it's digits is equal to the number itself. It's a specific case of Narcissistic Numbers. For example 407 is an Armstrong Number; because 4³ + 0³ + 7³ = 64 + 0 + 343 = 407. ## Further Reading [Wikipedia - Narcissistic/ Armstrong Number](https://en.wikipedia.org/wiki/Narcissistic_number) --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/mathematical_algorithms/src/armstrong_numbers/armstrong_number.php
<?php function is_armstrong($number) { $sum = 0; $dupli = $number; while($dupli != 0) { $digit = $dupli % 10; $sum += $digit * $digit * $digit; $dupli/=10; } return ($sum == $number); } if (is_armstrong(371)) echo "yes"; else echo "no"; ?>
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> int main() { int number, originalNumber, remainder, result = 0; printf("Enter a three digit integer: "); scanf("%d", &number); originalNumber = number; while (originalNumber != 0) { remainder = originalNumber % 10; result += remainder * remainder * remainder; originalNumber /= 10; } if (result == number) printf("%d is an Armstrong number.", number); else printf("%d is not an Armstrong number.", number); return (0); }
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.cpp
#include <iostream> #include <cmath> using namespace std; // Part of Cosmos by OpenGenus Foundation int main() { int initialNumber; int number; cout << "Enter a three digit number: "; cin >> initialNumber; number = initialNumber; int lastDigitCubed = pow(number % 10, 3); number /= 10; int middleDigitCubed = pow(number % 10, 3); number /= 10; int firstDigitCubed = pow(number % 10, 3); bool isArmstrongNumber = (firstDigitCubed + middleDigitCubed + lastDigitCubed) == initialNumber; cout << initialNumber << " is " << (isArmstrongNumber ? "" : "not ") << "an Armstrong number." << endl; }
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* * Armstrong number is a number that is equal to the sum of cubes of its digits. * For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers. * * */ namespace armstrong { class armstrong { int number; public armstrong(int number) { this.number = number; } public bool check() { if (number == getcSum()) return true; return false; } int getcSum() { int dupli = number; int sum = 0; while (dupli != 0) { sum += getcube(dupli % 10); dupli /= 10; } return sum; } int getcube(int number) { return number * number * number; } } class Program { static void Main(string[] args) { int num = 15; armstrong arm = new armstrong(num); if (arm.check()) Console.WriteLine("{0} is an armstrong number", num); else Console.WriteLine("{0} is not an armstrong number", num); Console.ReadKey(); // pauses the program } } }
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.go
package main import ( "fmt" "math" ) // Part of Cosmos by OpenGenus Foundation // Lists all possible armstrong numbers from 0 to 999 func listAM() { count := 0 for a := 0; a < 10; a++ { for b := 0; b < 10; b++ { for c := 0; c < 10; c++ { abc := (a * 100) + (b * 10) + (c) if abc == (cube(a) + cube(b) + cube(c)) { count++ fmt.Printf("%d: %d\n", count, abc) } } } } } func cube(n int) int { return int(math.Pow(float64(n), 3.0)) } func main() { listAM() }
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.java
import java.util.Scanner; class Main { //Main function public static void main(String args[]) { Scanner in = new Scanner(System.in);//Input from keyboard through Scanner class in Java System.out.println("Enter a 3-digit number : ");//Asking from user to enter a 3-digit number int number = in.nextInt();//Reading Integer input through keyboard using method int a = number % 10;//Getting remainder for number at unit place int b = (number / 10) % 10;//Number for ten's place int c = number / 100;//Number for hundretth place if ((a*a*a + b*b*b + c*c*c) == number) {//Condition to check System.out.println(number + " is a armstrong number.");//Output return } else { System.out.println(number + " is not a armstrong number.");//Output return } in.close();//Closing Scanner class } }
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.js
const readline = require("readline"); const ioInterface = readline.createInterface({ input: process.stdin, output: process.stdout }); ioInterface.question("Enter a three digit integer: ", answer => { var armstrong = answer .split("") .map(num => parseInt(num) ** 3) .reduce((elem, sum) => elem + sum); console.log( `${answer} is ${ armstrong == parseInt(answer) ? "" : "not " }an Armstrong number.` ); ioInterface.close(); });
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.py
""" Armstrong Number - In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. """ # Part of Cosmos by OpenGenus Foundation def Armstrong(num): order = len(str(num)) sum = 0 temp = num while temp > 0: digit = temp % 10 sum = sum + digit ** order temp = temp // 10 if sum == num: return True else: return False if __name__ == "__main__": Armstrong(407)
code/mathematical_algorithms/src/armstrong_numbers/armstrong_numbers.rb
# created by AnkDos # You can Simply use '**' to cube ,ex. 3**3=27 ,so cube(remainder) can be written as (reminder**3) def cube(num) num * num * num end def Is_armstrong(num) quotient = 1 reminder = 0 sum = 0 hold = num while quotient > 0 quotient = num / 10 reminder = num % 10 sum += cube(reminder) num = quotient end hold == sum end puts Is_armstrong(153).to_s # output => true
code/mathematical_algorithms/src/automorphic_numbers/README.md
# Automorphic Number In mathematics an automorphic number (sometimes referred to as a circular number) is a number whose square "ends" in the same digits as the number itself. For example, + 5<sup>2</sup> = 2**5** + 6<sup>2</sup> = 3**6** + 76<sup>2</sup> = 57**76** + 376<sup>2</sup> = 141**376** + 890625<sup>2</sup> = 793212**890625** So 5, 6, 76, 376 and 890625 are automorphic numbers. <br/><br/><br/><br/><br/> --- <p align="center">A massive collaborative effort by <a target="_blank" href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a></p> ---
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.c
/* * Part of Cosmos by OpenGenus. * Implementing automorphic numbers in C. * run code with gcc automorphicnumbers.c -lm as I use math library. */ #include <stdio.h> #include <math.h> int main() { long long int n , p, count=0, q; unsigned long long int k; /* The number is given by user for checking automorphism. */ scanf("%lld",&n); p = n; while (p) { /* While here we count that our number is in which range bsically we count number of digits in our number. */ count++; p = p / 10; } /* The ten power number just after our number for calculating mod value. */ q = pow(10, count); k = n * n; k = k % q; if (k == n) printf("Given number is automorphic.\n"); else printf("Given number is not automorphic.\n"); return (0); }
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.cpp
#include <iostream> #include <string> #include <algorithm> // For std::equal using namespace std; /* * In mathematics an automorphic number (sometimes referred to as a circular number) is a number * whose square "ends" in the same digits as the number itself. * For example, 5^2 = 25, 6^2 = 36, 76^2 = 5776, 376^2 = 141376,and 890625^2 = 793212890625, * so 5, 6, 76 and 890625 */ // Part of Cosmos by OpenGenus Foundation int main() { long long int number; // May have to deal with large numbers cout << "Enter a number: "; cin >> number; unsigned long long int numberSquared = number * number; // Squares can get really big string numberString = to_string(number); string numberSquaredString = to_string(numberSquared); bool isAutomorphic = std::equal(numberString.rbegin(), numberString.rend(), numberSquaredString.rbegin()); // Checks if the number is at the end of the number squared cout << number << " is " << (isAutomorphic ? "" : "not ") << "an automorphic number." << endl; }
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.cs
/* Part of Cosmos by OpenGenus Foundation */ using System; namespace AutomophicCSharp { class Automorphic { static void Main (string[] args) { for(double i=0; i<=10000000; i++) { if(isAutomorphic(i)) { Console.WriteLine(String.Format("{0} is automorphic - {1}", i, i*i)); } } } static bool isAutomorphic(double value) { // convert the value to a string string stringValue = value.ToString(); // get the square as a string string stringSquared = (value * value).ToString(); return stringSquared.EndsWith(stringValue); } } }
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.go
package main import ( "fmt" "strconv" ) func main() { for num := 0; num <= 1000000; num++ { if isAutomorphic(num) { fmt.Println(num, " ", (num * num)) } } } func isAutomorphic(num int) bool { strNum := strconv.Itoa(num) strSquareNum := strconv.Itoa(num * num) lenNum := len(strNum) lenSquareNum := len(strSquareNum) return strNum == strSquareNum[lenSquareNum-lenNum:] }
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.hs
--Automorphic number --An automorphic number is a number whose square "ends" in the same digits as the number itself. --Ex: 5^2 = 25, 6^2 = 36, 76^2 = 5776, 376^2 = 141376 --Compile: ghc --make automorphic.hs -o automorphic module Main where --Check number for automorphism automorphic :: Integer -> Bool automorphic n = (==) n $ automParse (n^2) n --Return last # digit values of number, # determined by second input automParse :: Integer -> Integer -> Integer automParse n = mod n . (10 ^) . subtract 1 . numDigits --Return number of digits in a number numDigits :: Integer -> Integer numDigits = (1+) . round . logBase 10 . fromIntegral --Infinite list of valid automorphic numbers. Beware high indices. --Ex: take 6 automList = [5,6,76,376,625,9376] automList = filter automorphic [1..] main :: IO () main = do putStrLn "Enter a number: " num <- readLn case automorphic num of True -> putStrLn "Number is automorphic." False -> putStrLn "Number is not automorphic."
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.java
// Part of Cosmos by OpenGenus Foundation class AutomorphicNumber{ public static void main(String[] args){ // From range 0 to 1000000, // it will find which one is Automorphic Number. // If it is Automorphic Number, // then program will print it with its square value. for(long x=0; x<=1000000; x++) if(automorphic(x)) // Square numbers can get really big. // So, if you want to try with a bigger number, I suggest // to use java.math.BigInteger instead of long data type. System.out.println(x+" "+(x*x)); } public static boolean automorphic(long num){ // Convert num into string data type. String strNum = Long.toString(num); // Convert num^2 into string data type. Like in the comment before, // use BigInteger, if you want to try a really big number. String strSquareNum = Long.toString(num*num); // Find the length of both converted num and num^2. int lenNum = strNum.length(); int lenSquareNum = strSquareNum.length(); // Return the value of (the last lenNum digits of num^2 == num) return strSquareNum.substring(lenSquareNum-lenNum).equals(strNum); } }
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.js
/** In mathematics an automorphic number (sometimes referred to as a circular number) is a number whose square "ends" in the same digits as the number itself. For example, 5^2 = 25, 6^2 = 36, 76^2 = 5776, 376^2 = 141376,and 890625^2 = 793212890625, so 5, 6, 76 and 890625 */ // Part of Cosmos by OpenGenus Foundation const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Enter a Number: ", num => { if (automorphic(num)) console.log(`${num} is an automorphic number.`); else console.log(`${num} is not an automorphic number.`); rl.close(); }); function automorphic(num) { return Math.pow(num, 2) % Math.pow(10, num.toString().length) == num; }
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.php
<?php function isAutomorphic(int $num) { return endsWith(strval($num * $num), strval($num)); } function endsWith($haystack, $needle) { $length = strlen($needle); return $length === 0 || (substr($haystack, -$length) === $needle); } echo "Automorphic number\n"; $test_data = [ 0 => true, 9 => false, 5 => true, 6 => true, 7 => false, 8 => false, 25 => true, 30 => false, ]; foreach ($test_data as $input => $expected) { $result = isAutomorphic($input); printf( " input %d, expected %s, got %s: %s\n", $input, ($expected ? 'true' : 'false'), ($result ? 'true' : 'false'), ($expected === $result) ? 'OK' : 'FAIL' ); }
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.py
""" In mathematics an automorphic number (sometimes referred to as a circular number) is a number whose square "ends" in the same digits as the number itself. For example, 5^2 = 25, 6^2 = 36, 76^2 = 5776, 376^2 = 141376,and 890625^2 = 793212890625, so 5, 6, 76 and 890625 """ # Part of Cosmos by OpenGenus Foundation def automorphic(num): order = len(str(num)) square_num = num ** 2 str_num = str(square_num) if str_num[len(str_num) - order :] == str(num): return True else: return False if __name__ == "__main__": if automorphic(138): print("Automorphic Number") else: print("Not Automorphic Number")
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.rb
def is_automorphic(x) x2 = (x**2).to_s; x = x.to_s x2_len = x2.length; x_len = x.length x == x2[x2.length - x.length..x2.length] end ## tests # automorphic [5, 6, 76, 376, 890_625].each do |num| num_squared = num**2 puts "#{num}^2 = #{num_squared} -> Automorphic: #{is_automorphic(num)}" end # not automorphic [2, 8, 75, 377, 890_620].each do |num| num_squared = num**2 puts "#{num}^2 = #{num_squared} -> Automorphic: #{is_automorphic(num)}" end
code/mathematical_algorithms/src/automorphic_numbers/automorphic_numbers.swift
#!/usr/bin/env swift // Part of Cosmos by OpenGenus Foundation func automorphic(num:Int)-> Bool{ let strNum = String(num) let strSquaredNum = String(num*num) let check = strSquaredNum.hasSuffix(strNum) if(check){ return true } else{ return false } } let number = Int(readLine()!) let result = automorphic(num:number!) if(result == true){ print("Automorphic number") } else{ print("Not automorphic number") }
code/mathematical_algorithms/src/average_stream_numbers/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/average_stream_numbers/average_stream_numbers.c
#include <stdio.h> float getAvg(float prev_avg, int x, int n) { return (((prev_avg * n) + x) / (n + 1)); } void streamAvg(float arr[], int n) { float avg = 0; for (int i = 0; i < n; i++) { avg = getAvg(avg, arr[i], i); printf("Average of %d numbers is %f \n", i + 1, avg); } } int main() { int n; printf("Enter Array Size \n"); scanf("%d", &n); float arr[n]; printf("Enter %d Integers \n", n); for (int i = 0; i < n; i++) scanf("%f", &arr[i]); streamAvg(arr, n); return (0); }
code/mathematical_algorithms/src/average_stream_numbers/average_stream_numbers.cpp
#include <iostream> #include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation double getAverage(double num) { static double sum = 0, n = 0; sum += num; return sum / ++n; } void streamAverage(vector<double> arr) { double average = 0; for (size_t i = 0; i < arr.size(); i++) { average = getAverage(arr[i]); cout << "Average of " << i + 1 << " numbers is " << average << endl; } } int main() { vector<double> arr{10, 20, 30, 40, 50, 60}; streamAverage(arr); return 0; }
code/mathematical_algorithms/src/average_stream_numbers/average_stream_numbers.go
package main // Part of Cosmos by OpenGenus Foundation import "fmt" func averageStreamNumbers(input []int) { average := 0 sum := 0 n := 0 getAverage := func(input int) int { sum += input n++ return sum / n } for i := range input { average = getAverage(input[i]) fmt.Printf("Average of %d numbers is %d\n", i+1, average) } } func main() { input := []int{10, 20, 30, 40, 50, 60, 70, 80} averageStreamNumbers(input) }
code/mathematical_algorithms/src/average_stream_numbers/average_stream_numbers.js
/* Part of Cosmos by OpenGenus Foundation */ function iterativeAverage(arr) { let sum = 0 arr.forEach((eachnum, index) => { sum += eachnum console.log(`Average of ${index + 1} numbers is ${sum/(index + 1)}`) }) } iterativeAverage([1, 9, 20, 13, 45])
code/mathematical_algorithms/src/average_stream_numbers/average_stream_numbers.py
# Part of Cosmos by OpenGenus Foundation def newAvg(prevAvg, newN, newX): return (prevAvg * (newN - 1) + newX) / newN def main(): L = [1, 9, 20, 13, 45] avg = 0 for i in range(len(L)): avg = newAvg(avg, (i + 1), L[i]) print(avg) main()
code/mathematical_algorithms/src/babylonian_method/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/babylonian_method/babylonian_method.c
#include<stdio.h> double squareRoot(double num) { double error = 0.0000001; double x = num; while ((x - num / x) > error) x = (x + num / x) / 2; return (x); } int main() { double num = 0; printf("Enter number for finding square root:"); scanf("%lf", &num); printf("Square root of %lf is %lf\n", num, squareRoot(num)); return (0); }
code/mathematical_algorithms/src/babylonian_method/babylonian_method.cpp
#include <iostream> using namespace std; float squareRoot(int x) { float i = x; float e = 0.000001; while (i - (x / i) > e) i = (i + (x / i)) / 2; return i; } int main() { int x; cin >> x; cout << "Square root of " << x << " is " << squareRoot(x); return 0; }
code/mathematical_algorithms/src/babylonian_method/babylonian_method.go
package main import "fmt" func squareRoot(n int) float64 { x := float64(n) nF := float64(n) e := 0.000001 for x - (nF/x) > e { x = ((nF/x)+x)/2 } return x } func main() { a := 90 fmt.Printf("The square root of %v is %v \n", a, squareRoot(a)) }
code/mathematical_algorithms/src/babylonian_method/babylonian_method.java
import java.util.*; class Babylonian{ public static void main(String args[] ) throws Exception { Scanner s = new Scanner(System.in); double n = s.nextDouble(); System.out.println("The square root of " + n + " is " + squareRoot(n)); } /*Returns the square root of n*/ public static double squareRoot(double n) { double x = n; double y = 1; double acc = 0.000001; /* acc decides the accuracy level*/ while(x - y > acc) { x = (x + y)/2; y = n/x; } return x; } }
code/mathematical_algorithms/src/babylonian_method/babylonian_method.js
function b_sqrt(n, e = 1e-5) { var x = n; while (x - n / x > e) { x = (n / x + x) / 2; } return x; } console.log(b_sqrt(90));
code/mathematical_algorithms/src/babylonian_method/babylonian_method.py
def squareRoot(n): x = n y = 1 e = 0.000001 while x - y > e: x = (x + y) / 2 y = n / x return x print(squareRoot(50))
code/mathematical_algorithms/src/binary_to_decimal/Conversion_from_Binary_to_Decimal.cpp
#include <bits/stdc++.h> using namespace std; int binary_to_decimal(int number) { int i, remainder, store, output; remainder = 1; store = 1; output = 0; for (i = 0; number > 0; i++) { remainder = number % 10; store = remainder * (pow(2, i)); output = output + store; number = number / 10; } return output; } int main() { int numberInput; cin >> numberInput; cout << binary_to_decimal(numberInput) << endl; return 0; }
code/mathematical_algorithms/src/binary_to_decimal/Conversion_from_Binary_to_Decimal.py
def check_binary(st): p = set(st) s = {'0', '1'} if s==p or p=={'0'} or p=={'1'}: return 1 else: return 0 def binary_to_decimal(number): i = 0 output = 0 while number > 0: rem = int(number % 10) store = rem * pow(2,i) output = output + store number = int(number / 10) i = i + 1 return output numberInput = int(input("Enter the binary number: ")) while check_binary(str(numberInput)) != 1: print("Sorry, You entered non binary number") numberInput = int(input("Enter the binary number: ")) print(f"{numberInput} in decimal is {binary_to_decimal(numberInput)}")
code/mathematical_algorithms/src/binomial_coefficient/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/binomial_coefficient/binomial_coefficient.c
#include <stdio.h> long long int a[101][101]; void pascal() { int i, j; for (i = 0; i < 101; i++) { for (j = 0; j <= i; j++) { if (j == 0 || j == i) a[i][j] = 1; else a[i][j] = a[i - 1][j - 1] + a[i - 1][j]; } } } int main() { int n, r; printf("Enter n: "); scanf("%d", &n); printf("Enter r: "); scanf("%d", &r); pascal(); printf("%dC%d = %lli\n", n, r, a[n][r]); return (0); }
code/mathematical_algorithms/src/binomial_coefficient/binomial_coefficient.cpp
#include <iostream> using namespace std; //Calculation C(n, r) modulo any number (prime or composite) using pascal triangle //Pre-computation : O(n^2) const int MAX = 1e3 + 3; const int MOD = 1e9 + 7; int ncr[MAX][MAX]; void pascal() { for (int i = 0; i < MAX; ++i) { ncr[i][0] = ncr[i][i] = 1; for (int j = 1; j < i; ++j) { ncr[i][j] = ncr[i - 1][j - 1] + ncr[i - 1][j]; if (ncr[i][j] >= MOD) ncr[i][j] -= MOD; } } } int main() { pascal(); cout << "Binomial Coefficient of (10, 5) is " << ncr[10][5] << "\n"; return 0; }
code/mathematical_algorithms/src/binomial_coefficient/binomial_coefficient.go
package main // Part of Cosmos by OpenGenus Foundation import ( "fmt" ) func binomialCoefficient(n int, k int) float64 { bc := make([][]float64, n+1) for i := range bc { bc[i] = make([]float64, n+1) } for i := 0; i <= n; i++ { bc[i][0] = 1; } for i := 0; i <= n; i++ { bc[i][i] = 1; } for i := 1; i <= n; i++ { for j := 1; j < i; j++ { bc[i][j] = bc[i-1][j-1] + bc[i-1][j] } } return bc[n][k]; } func main() { fmt.Println(binomialCoefficient(10,5)) }
code/mathematical_algorithms/src/binomial_coefficient/binomial_coefficient.java
public class BinomialCoefficient { // Part of Cosmos by OpenGenus Foundation public long solve(int n, int k) { long bc[][] = new long[n+1][n+1]; for(int i = 0; i <= n; i++) { bc[i][0] = 1; } for(int j = 0; j <= n; j++) { bc[j][j] = 1; } for(int i = 1; i <= n; i++) { for(int j = 1; j < i; j++) { bc[i][j] = bc[i-1][j-1] + bc[i-1][j]; } } return bc[n][k]; } public static void main(String[] args) { BinomialCoefficient solver = new BinomialCoefficient(); System.out.println(solver.solve(10,5)); } }
code/mathematical_algorithms/src/binomial_coefficient/binomial_coefficient.py
# Part of Cosmos by OpenGenus Foundation def binomialCoeff(n, k): C = [0 for i in range(k + 1)] C[0] = 1 for i in range(1, n + 1): j = min(i, k) while j > 0: C[j] = C[j] + C[j - 1] j -= 1 return C[k] n = int(input()) k = int(input()) print(binomialCoeff(n, k))
code/mathematical_algorithms/src/catalan_number/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter # Catalan Number The Catalan numbers are a sequence of natural numbers that have applications in the area of combinatorial mathematics. The firsts Catalan numbers are: 1, 1, 2, 5, 14, 42, 132, 429, 1430... --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/mathematical_algorithms/src/catalan_number/catalan_number.c
/* Part of Cosmos by OpenGenus Foundation. */ #include <stdio.h> /* * Returns value of Binomial Coefficient C(n, k). */ unsigned long int binomial_Coeff(unsigned int n, unsigned int k) { unsigned long int res = 1; int i ; /* Since C(n, k) = C(n, n-k) */ if (k > n - k) k = n - k; /* Calculate value of nCk */ for (i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return (res); } /* * A Binomial coefficient based function to find nth catalan * O(n) time Solution. */ unsigned long int catalan(unsigned int n) { /* Calculate value of 2nCn */ unsigned long int c = binomial_Coeff(2 * n, n); /* return 2nCn/(n+1) */ return (c / (n+1)); } /* Driver program to test above functions. */ int main() { unsigned int n; printf("Input n \nNth Catalan you want :"); scanf("%d", &n); printf("Nth Catalan number is: %lu", catalan(n)); return (0); }
code/mathematical_algorithms/src/catalan_number/catalan_number.java
// Part of Cosmos by OpenGenus Foundation import java.util.HashMap; import java.util.Map; public class CatalanNumber { private static final Map<Long, Double> facts = new HashMap<Long, Double>(); private static final Map<Long, Double> catsI = new HashMap<Long, Double>(); private static final Map<Long, Double> catsR1 = new HashMap<Long, Double>(); private static final Map<Long, Double> catsR2 = new HashMap<Long, Double>(); static{//pre-load the memoization maps with some answers facts.put(0L, 1D); facts.put(1L, 1D); facts.put(2L, 2D); catsI.put(0L, 1D); catsR1.put(0L, 1D); catsR2.put(0L, 1D); } private static double fact(long n){ if(facts.containsKey(n)){ return facts.get(n); } double fact = 1; for(long i = 2; i <= n; i++){ fact *= i; //could be further optimized, but it would probably be ugly } facts.put(n, fact); return fact; } private static double catI(long n){ if(!catsI.containsKey(n)){ catsI.put(n, fact(2 * n)/(fact(n+1)*fact(n))); } return catsI.get(n); } private static double catR1(long n){ if(catsR1.containsKey(n)){ return catsR1.get(n); } double sum = 0; for(int i = 0; i < n; i++){ sum += catR1(i) * catR1(n - 1 - i); } catsR1.put(n, sum); return sum; } private static double catR2(long n){ if(!catsR2.containsKey(n)){ catsR2.put(n, ((2.0*(2*(n-1) + 1))/(n + 1)) * catR2(n-1)); } return catsR2.get(n); } public static void main(String[] args){ for(int i = 0; i <= 15; i++){ System.out.println(catI(i)); System.out.println(catR1(i)); System.out.println(catR2(i)); } } }
code/mathematical_algorithms/src/catalan_number/catalan_number.js
function binomial_Coeff(n, k) { let res = 1; if (k > n - k) { k = n - k; } for (let i = 0; i < k; i++) { res *= n - i; res /= i + 1; } return res; } function catalan(n) { const c = binomial_Coeff(2 * n, n); return c / (n + 1); } for (let j = 0; j < 10; j++) { console.log(catalan(j)); }
code/mathematical_algorithms/src/catalan_number/catalan_number.py
# Part of Cosmos by OpenGenus Foundation def catalan(n): if n <= 1: return 1 res = 0 for i in range(n): res += catalan(i) * catalan(n - i - 1) return res for i in range(10): print(catalan(i), emd=" ")
code/mathematical_algorithms/src/catalan_number/catalan_number.rb
def catalan(num) return 1 if num <= 1 ans = 0 i = 0 while i < num first = catalan i second = catalan num - i - 1 ans += (first * second) i += 1 end ans end Integer x = 1 while x <= 10 res = catalan x puts res x += 1 end
code/mathematical_algorithms/src/catalan_number/catalan_number.scala
object Catalan { def number(n: Int): BigInt = { if (n < 2) { 1 } else { val (top, bottom) = (2 to n).foldLeft((BigInt(1), BigInt(1))) { case ((topProd: BigInt, bottomProd: BigInt), k: Int) => (topProd * (n + k), bottomProd * k) } top / bottom } } // to test // var c = catalan(3) // println(c) def recursive(n: Int): Int = { if (n <= 1) 1 else (0 until n).map(i => recursive(i) * recursive(n - i - 1)).sum } } object Main { def main(args: Array[String]): Unit = { for (n <- 0 until 20) { println(s"${n}: ${Catalan.number(n)}") } } }
code/mathematical_algorithms/src/catalan_number/catalan_number2.py
def catalanNum(n): if n <= 1: return 1 result = 0 for i in range(n): result += catalanNum(i) * catalanNum(n - i - 1) return result for i in range(15): print(catalanNum(i))
code/mathematical_algorithms/src/catalan_number/catalan_number_dynamic.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation int main() { int n; cin >> n; long long cat[100000]; cat[0] = 1; cout << cat[0]; for (int i = 1; i <= n; i++) { cat[i] = 2 * (4 * i + 1) * cat[i - 1] / (i + 2); cout << cat[i] << endl; } }
code/mathematical_algorithms/src/catalan_number/catalan_number_recursive.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation int main() { int n; cin >> n; long long cat[100000]; cat[0] = 1; cout << cat[0]; for (int i = 1; i <= n; i++) { cat[i] = 0; for (int j = 0; j < i; j++) cat[i] += cat[j] * cat[i - j - 1]; cout << cat[i] << endl; } }
code/mathematical_algorithms/src/check_good_array_GCD_problem/GCD_related_problems.py
import math class Solution: def isGoodArray(self, nums: List[int]) -> bool: ''' ' 1. This problem is equivalent to "find two number and its linear combination equal to 1", ' Because If we can find two number and take coefficient of other numbers is zero. ' ' 2. Then this problem be considered as "find two number and they are coprime", ' Bacause this the EX_GCD conclude ' ' 3. So far, we should solve "find two number are coprime from a array", ' we can to calculate all number gcd whether is equal 1, ' exmaple1: gcd(a1, gcd(a2, gcd(a3, a4))) If its result is 1, then exist two or more number is coprime ' because once its intermediate result has 1 when the array have coprime number pair, then gcd(1, anynumber) = 1 ''' ans = nums[0] for num in nums: ans = math.gcd(ans, num) return ans == 1
code/mathematical_algorithms/src/check_good_array_GCD_problem/readme.md
Problem Description Given an array `nums` of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return `True` if the array is good otherwise return `False`. Example ``` Input: nums = [12,5,7,23] Output: true Explanation: Pick numbers 5 and 7. 5*3 + 7*(-2) = 1 ``` ``` Input: nums = [3,6] Output: false ```
code/mathematical_algorithms/src/check_is_square/check_is_square.c
#include <stdio.h> #include <math.h> int main() { int n, sqrt_n; scanf("%d", &n); sqrt_n = sqrt(n); if (sqrt_n * sqrt_n == n) printf("Natural Square number \n"); else printf("Not a Natural Square \n"); return (0); }
code/mathematical_algorithms/src/check_is_square/check_is_square.cpp
// Part of Cosmos by OpenGenus Foundation #include <iostream> using namespace std; typedef long long int lld; bool IsSquare(lld number) { lld min = 1; lld max = number; lld mid = min + (max - min) / 2; if (number == 0 || number == 1) return true; while (min < max) { if (mid * mid > number) { max = mid - 1; mid = min + (max - min) / 2; } else if (mid * mid < number) { min = mid + 1; mid = min + (max - min) / 2; } if (mid * mid == number) return true; } return false; } int main() { int t; cout << "Enter the number of testcases:" << '\n'; cin >> t; lld number; while (t--) { cin >> number; if (IsSquare(number)) cout << "Natural Square number" << '\n'; else cout << "Not a Natural Square" << '\n'; } return 0; }
code/mathematical_algorithms/src/check_is_square/check_is_square.cs
// Part of Cosmos by OpenGenus Foundation using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace finding_is_square { /// <summary> /// Class to check if number is a perfect square or not /// </summary> class is_square { /// <summary> /// an array to store numbers /// </summary> int[] numbers; /// <summary> /// constructor /// </summary> /// <param name="number">numbers to be processed</param> public is_square(int[] number) { numbers = number; } /// <summary> /// method to check if perfect square or not /// </summary> public void check_sq() { foreach (int number in numbers) // traversing the whole integer array { if (Math.Sqrt(number).ToString().Contains(".")) // converting double to string to chk if it contains . or not Console.WriteLine("number {0} is not a perfect square", number); else Console.WriteLine("number {0} is a perfect square", number); } } } class Program { static void Main(string[] args) { // making an array of numbers to check int[] numbers = { 56, 90, 100, 80, 16 }; // creating an object of is_square class and initializing with test inputs is_square sq = new is_square(numbers); sq.check_sq(); // checking Console.ReadKey(); // pausing } } }
code/mathematical_algorithms/src/check_is_square/check_is_square.go
// Part of Cosmos by OpenGenus Foundation package main import "fmt" import "math" func isSquare(input int) bool { if input < 0 { return false } root := int(math.Sqrt(float64(input))) return root*root == input } func main() { fmt.Printf("%d is square :%v\n", 16, isSquare(16)) fmt.Printf("%d is square :%v\n", 13, isSquare(13)) fmt.Printf("%d is square :%v\n", 316, isSquare(316)) }
code/mathematical_algorithms/src/check_is_square/check_is_square.java
// Part of Cosmos by OpenGenus Foundation import java.util.Scanner; public class CheckisSquare{ private static boolean checkIsSquare(int n){ if (n < 0) { return false; } else { int start = 0; int end = n; while (start <= end) { int mid = start + (end - start) / 2; long val = (long) mid * (long) mid; if (val == n) return true; else if (val < n) start = mid + 1; else end = mid - 1; } } return false; } public static void main(String[] args) { System.out.print("Please enter number: "); Scanner enterN = new Scanner(System.in); int n = enterN.nextInt(); if (checkIsSquare(n)) { System.out.println("True"); } else { System.out.println("False"); } } }
code/mathematical_algorithms/src/check_is_square/check_is_square.js
let isPerfectSquare = num => Math.sqrt(num) === Math.floor(Math.sqrt(num)); console.log(isPerfectSquare(0)); // should output true console.log(isPerfectSquare(1)); // should output true console.log(isPerfectSquare(2)); // should output false console.log(isPerfectSquare(4)); // should output true console.log(isPerfectSquare(8)); // should output false console.log(isPerfectSquare(16)); // should output true console.log(isPerfectSquare(32)); // should output false console.log(isPerfectSquare(64)); // should output true
code/mathematical_algorithms/src/check_is_square/check_is_square.kt
/* * Part of Cosmos by OpenGenus Foundation */ import kotlin.math.* fun checkSquare(number: Int) : Boolean { return sqrt(number.toDouble()) == floor(sqrt(number.toDouble())); } fun main() { println(checkSquare(0)); // true println(checkSquare(1)); // true println(checkSquare(2)); // false println(checkSquare(4)); // true println(checkSquare(8)); // false println(checkSquare(16)); // true println(checkSquare(32)); // false println(checkSquare(64)); // true }
code/mathematical_algorithms/src/check_is_square/check_is_square.php
<?php // Part of Cosmos by OpenGenus Foundation // function to check if a number is function check($numbers) { foreach ($numbers as $number) // traversing through each number { $chk = (string)sqrt($number) ; // sqrt returns float which is converted to string by explixit type casting if(strpos($chk,".")) // checking if there is decimal or not echo "$number is not a perfect square<br>"; else echo "$number is a perfect square<br>"; } } // array of numbers to be performed $numbers = array(1,2,3,4,5,6,7,8,9,10); check($numbers); // calling the function ?>
code/mathematical_algorithms/src/check_is_square/check_is_square.py
# Part of Cosmos by OpenGenus Foundation import sys def checkIfSquare(n): start = 0 end = int(n) while start <= end: mid = (start + end) // 2 val = mid * mid if val == int(n): return True elif val < int(n): start = mid + 1 else: end = mid - 1 return False version = sys.version_info[0] print("Enter a positive number :") n = input() if checkIfSquare(n): print("Yes") else: print("No")
code/mathematical_algorithms/src/check_is_square/check_is_square.rs
// Part of Cosmos by OpenGenus Foundation //-- Function to check if a number is square //-- Accepts integers, and converts it internally to float use std::f64; fn check_square(n: i64 ) -> bool { if n < 0 { return false; } let nc = n as f64; let r = nc.sqrt().round(); if r * r == nc { return true; } false } fn main() { let test = vec!(1,2,3,4,5,6,7,8,9,10); for t in test { println!("{}: {}", t, check_square(t)); } }
code/mathematical_algorithms/src/check_is_square/check_is_square.ruby
# let isPerfectSquare = num => Math.sqrt(num) === Math.floor(Math.sqrt(num)) # console.log(isPerfectSquare(0)) // should output true # console.log(isPerfectSquare(1)) // should output true # console.log(isPerfectSquare(2)) // should output false # console.log(isPerfectSquare(4)) // should output true # console.log(isPerfectSquare(8)) // should output false # console.log(isPerfectSquare(16)) // should output true # console.log(isPerfectSquare(32)) // should output false # console.log(isPerfectSquare(64)) // should output true def perfect_square?(num) Math.sqrt(num) % 1 == 0 end puts perfect_square?(0) # should output true puts perfect_square?(1) # should output true puts perfect_square?(2) # should output false puts perfect_square?(4) # should output true puts perfect_square?(8) # should output false puts perfect_square?(16) # should output true puts perfect_square?(32) # should output false puts perfect_square?(64) # should output true
code/mathematical_algorithms/src/check_is_square/check_is_square.scala
// Part of Cosmos by OpenGenus Foundation object FindingSquare extends App{ def findingSquare(num:Int):Boolean = { for(x <- 1 to num if x * x <= num){ if(x * x == num) return true } false } def printResult(num:Int){ findingSquare(num) match{ case true => println(s"$num is perfect square") case false => println(s"$num is not perfect square") } } printResult(3) printResult(4) }
code/mathematical_algorithms/src/check_is_square/check_is_square.swift
#!/usr/bin/env swift // Part of Cosmos by OpenGenus Foundation import Darwin func findingSquare(num : Int) -> Bool { let x = Int(sqrt(Double(num))) for i in 0...x{ if(i*i == num){ return true } } return false } let number = Int(readLine()!) let result = findingSquare(num: number!) if(result){ print("A perfect square") } else{ print("Not a perfect square") }