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) ## Ex...
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){ ...
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); } /* -------------------------------------- A...
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 ...
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[...
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.leng...
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) ...
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...
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<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; } ...
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 re...
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 >>...
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 ...
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 No...
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 = ...
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 ...
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)...
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) { ...
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, ...
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 ...
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 ...
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 no...
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 { ...
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...
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);...
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)) ...
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...
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; ...
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; ...
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 armstr...
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)...
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();//Readin...
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)...
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 + dig...
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(remi...
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>...
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 check...
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 =...
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...
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(...
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 ...
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(au...
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 ...
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 =...
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 ...
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 automorp...
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(...
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("...
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++) ...
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 ...
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); prin...
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 stati...
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; ...
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...
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(...
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; ...
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;...
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++) {...
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 ...
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; /...
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> cats...
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) }...
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 -...
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 p...
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 goo...
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 * mi...
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 { ...
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"...
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 ...
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(isPerfectS...
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 print...
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,"."))...
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: ...
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; } ...
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(isP...
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 fal...
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: nu...