filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/mathematical_algorithms/src/newton_raphson_method/newton_raphson.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <cmath>
#include <iostream>
#include <limits>
#include <string>
#include <stdexcept>
// This code requires you to enable the C++11 standard when compiling
void helpAndExit()
{
std::cout << "Newton-Raphson iteration for the function x*log10(x)-1.2\n"
... |
code/mathematical_algorithms/src/newton_raphson_method/newton_raphson.php | <?php
$intervalOne = 3;
$intervalTwo = 4;
$maxIteration = 10;
$precision = 0.001;
//example function = x³ - 4x² + 2
function f($x){
return (($x ** 3) - (4 * ($x ** 2)) + 2);
}
//derivate 3x² - 8x
function df($x){
return ((3 * ($x ** 2)) - (8 * $x));
}
function firstIterationValue($interN,$interM){
$first... |
code/mathematical_algorithms/src/next_larger_number/next_larger_number.cpp | #include <iostream>
#include <algorithm>
#include <cstring>
// Part of Cosmos by OpenGenus Foundation
void nextgr(char num[], int n)
{
int i, j;
for (i = n - 1; i >= 0; --i)
if (num[i - 1] < num[i])
break;
if (i == 0)
{
std::cout << "No such greater number exists";
... |
code/mathematical_algorithms/src/next_larger_number/next_larger_number.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* Finds next greater number containing only digits from input number
*
* @param int $num input number
* @return int|false next greater number or false if it does not exist
*/
function next_larger_number(int $num)
{
$arr = array_map('intval', str_spl... |
code/mathematical_algorithms/src/next_larger_number/next_larger_number.py | # Python program to find the smallest number which
# is greater than a given no. has same set of
# digits as given number
# Part of Cosmos by OpenGenus Foundation
# Given number as int array, this function finds the
# greatest number and returns the number as integer
def findNext(number, n):
# Start from the right... |
code/mathematical_algorithms/src/pandigital_number/README.md | ## What is a pandigital number?
In mathematics, a pandigital number is an integer that in a given base has among its significant digits each digit used in the base at least once. For example, 1223334444555556666667777777888888889999999990 is a pandigital number in base 10.
---
<p align="center">
A massive collabora... |
code/mathematical_algorithms/src/pandigital_number/pandigital_number.c | // Part of Cosmos by OpenGenus Foundation
#include "stdio.h"
#include "string.h"
int is_pandigital(long long number, int base);
int is_zeroless_pandigital(long long number, int base);
int check_number(long long number, int base);
int main(){
long long number;
int base;
printf("Enter a number: ");
scanf("%lld", &... |
code/mathematical_algorithms/src/pandigital_number/pandigital_number.rb | def is_pandigital(num)
digits = (1 << 10) - 1
while num > 0
dgt = num % 10
dgt_map = ((1 << 10) - 1) - (1 << dgt)
digits &= dgt_map
num /= 10
end
digits == 0
end
def is_zeroless_pandigital(num)
digits = (1 << 9) - 1
while num > 0
dgt = num % 10
return false if dgt == 0
dgt_map =... |
code/mathematical_algorithms/src/pascal_triangle/README.md | # Pascal Triangle
The Pascal Triangle is a triangular array of the binomial coefficients.
To build a Pascal Triangle; start at row 0 by placing a 1; then each consecutive row will have one more
element, and each element will be the sum of the number above and to the left with the number above and to the right (blank e... |
code/mathematical_algorithms/src/pascal_triangle/pascal_triangle.c | #include <stdio.h>
long long int a[101][101];
void pascal_triangle()
{
for(int i=0;i<101;i++){
for(int 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;
scanf("%d",&n);
pascal_triangle();
for(int i=0;i<=n;i++){
for(int j=0;... |
code/mathematical_algorithms/src/pascal_triangle/pascal_triangle.cpp | #include <iostream>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
typedef vector<int> vi;
typedef vector<vi> vvi;
// construct triangle with rows 0...n
// pascal[i][j] = 0 iff i < j
vvi pascal_triangle(int n)
{
vvi pascal(n + 1, vi(n + 1));
for (int i = 0; i <= n; ++i)
... |
code/mathematical_algorithms/src/pascal_triangle/pascal_triangle.exs | defmodule PascalTriangle do
def draw(1), do: (IO.puts("1"); [1])
def draw(current_level) do
list = draw(current_level - 1)
new_list = [1] ++ for(x <- 0..length(list)-1, do: Enum.at(list, x) + Enum.at(list, x+1, 0))
Enum.join(new_list, " ") |> IO.puts
new_list
end
end
PascalTriangle.draw(7)
|
code/mathematical_algorithms/src/pascal_triangle/pascal_triangle.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
// N choose K
func combination(n int, k int) int {
prod := 1
if n < k {
return 0
}
if k > n/2 { // Optimize number of multiplications
k = n - k
}
for i := 1; i <= k; i++ {
prod = prod * (n - i + 1) /... |
code/mathematical_algorithms/src/pascal_triangle/pascal_triangle.java | // Part of Cosmos by OpenGenus Foundation
import java.util.Scanner;
public class pascal_triangle {
private static Integer[][] PascalTriangle(int n) {
Integer[][] matrix = new Integer[n][n];
for (int i = 0; i < n; ++i) {
matrix[i][0] = matrix[i][i] = 1;
for (int f = 1; f < ... |
code/mathematical_algorithms/src/pascal_triangle/pascal_triangle.py | import math
# pascals_tri_formula =
print("Enter a number : ")
inp = int(input())
def combination(n, r): # correct calculation of combinations, n choose k
return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r)))
def for_test(x, y): # don't see where this is being used...
for y in r... |
code/mathematical_algorithms/src/perfect_number/.gitignore | *.class
*.jar
|
code/mathematical_algorithms/src/perfect_number/README.md | # Perfect Numbers
In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.
The first perfect number is 6. Its proper divisors are 1, 2, and 3, and 1 + 2 + 3 = 6.
The next perfect number i... |
code/mathematical_algorithms/src/perfect_number/perfect_number.c | #include <stdio.h>
int main()
{
int number, rem, sum = 0, i;
printf("Enter a Number\n");
scanf("%d", &number);
for (i = 1; i <= (number - 1); i++)
{
rem = number % i;
if (rem == 0)
{
sum = sum + i;
}
}
if (sum == number)
printf("Entered Number is perfect number");
else
printf("Entered Number is not a perfect
number");
... |
code/mathematical_algorithms/src/perfect_number/perfect_number.cpp | #include <iostream>
using namespace std;
int main()
{
int num, sum = 0, i;
cout << "ENTER A NUMBER: ";
cin >> num;
for (i = 1; i < num; i++)
if (num % i == 0)
sum = sum + i;
cout << "\n";
if (sum == num)
cout << num << " IS A PERFECT NUMBER\n";
else
... |
code/mathematical_algorithms/src/perfect_number/perfect_number.hs | --Perfect Number
module PerfectNumber where
perfectNum :: Integer -> Bool
perfectNum n = factorSum n == n
factorSum :: Integer -> Integer
factorSum n = sum [x | x <- [1..n], mod n x == 0, x < n]
perfectList = map perfectNum [1..] |
code/mathematical_algorithms/src/perfect_number/perfect_number.java | import java.util.Scanner;
public final class perfect_number {
private static boolean hasPerfect = false;
public static void main(String[] args){
final Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
for (int i = ... |
code/mathematical_algorithms/src/perfect_number/perfect_number.js | const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Enter a Number: ", number => {
let hasPerfect = false;
number = parseInt(number, 10);
for (let i = 6; i < number; i++) {
if (isPerfect(i)) {
console.log(i + " ... |
code/mathematical_algorithms/src/perfect_number/perfect_number.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param int $n
*
* @return bool
*/
function isPerfectNumber($n)
{
$sum = 0;
for ($i = 1; $i < $n; $i++) {
if ($n % $i === 0) {
$sum += $i;
}
}
return $sum === $n;
}
echo isPerfectNumber($number = 6) ? sprintf('%d i... |
code/mathematical_algorithms/src/perfect_number/perfect_number.py | def is_perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
num = int(input("Please enter a number to check if it is perfect or not"))
print(is_perfect_number(num))
|
code/mathematical_algorithms/src/perfect_number/perfect_number.rb | def perfect(i)
sum = 0
for n in 1..i - 1
sum += n if i % n == 0
end
if sum == i
p `#{i} is perfect number`
else
p `#{i} isn't perfect number`
end
end
puts 'Enter the number to check: '
perfect gets.chomp.to_i
|
code/mathematical_algorithms/src/perfect_number/perfect_number.rs | /// Perfect number is a positive integer that is equal to the sum of its proper divisors.
fn is_perfect(num: i32) -> bool {
let mut sum = 0;
for i in 1..num {
if num % i == 0 {
sum += i;
}
}
if sum == num {
true
} else {
false
}
}
fn main() {
f... |
code/mathematical_algorithms/src/perfect_number/perfect_number_list.cpp | #include <iostream>
#include <vector>
using namespace std;
bool is_perfect(int);
int main()
{
int max = 8129;
cout << "List of perfect numbers between 1 and " << max << ": " << endl;
for (int i = 6; i < max; i++)
if (is_perfect(i))
cout << i << ", ";
}
bool is_perfect(int p_num_to_ch... |
code/mathematical_algorithms/src/permutation_lexicographic_order/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/permutation_lexicographic_order/permutation_lexicographic_order.cpp | #include <iostream>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
set<string> s;
void permutation(string a, int i = 0)
{
if (a[i] == '\0')
{
// cout << a << endl;
s.insert(a);
return;
}
for (int j = i; a[j] != '\0'; j++)
{
swap(a[i], a[j... |
code/mathematical_algorithms/src/poisson_sample/poisson_sample.py | from random import random
from math import exp
from math import factorial
def poisson_sample(mean, n=1):
"Return a list containing n samples from a Poisson distribution with specified mean"
sample = []
for i in range(n):
rand_num = random() # get a uniform random number in [0, 1)
count = ... |
code/mathematical_algorithms/src/power/method1_power_recursion_with_even_odd_optimization.cpp | #include<bits/stdc++.h>
using namespace std;
// O(log2(p))
long long power(int base,int p){
if(p==0)
return 1;
else if(p%2==0)
return power(base*base,p/2);
else if(p%2==1)
return base*power(base*base,p/2);
}
int main(){
int base,p;
while(cin>>base>>p){
cout<< ... |
code/mathematical_algorithms/src/power/method2_power_recursion_with_even_odd_optimization.cpp | #include<bits/stdc++.h>
using namespace std;
// O(log2(p))
int power(int base,int p,int mod){
if(p==0)
return 1;
else if(p%2==0)
return power( ((base %mod)*(base %mod)) %mod, p/2, mod);
else if(p%2==1)
return ( (base%mod) * (power(((base %mod)*(base %mod))%mod, p/2, mod) %mod)) %... |
code/mathematical_algorithms/src/primality_tests/fermat_primality_test/fermat_primality_test.c | /**
* C program to implement Fermat's Primality Test
* based on Fermat's little theorem
* Part of Cosmos by OpenGenus Foundation
**/
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define ITERATIONS 100// number of iterations to run the test
//function to calculate modulo using exponential squaring t... |
code/mathematical_algorithms/src/primality_tests/fermat_primality_test/fermat_primality_test.py | from random import randint
def isPrime(n, k=10):
if n <= 1:
return False
if n <= 3:
return True
for i in range(k):
a = randint(2, n - 1)
if pow(a, n - 1, n) != 1:
return False
return True
if __name__ == "__main__":
if isPrime(103):
print("Prime... |
code/mathematical_algorithms/src/primality_tests/miller_rabin_primality_test/miller_rabin_primality_test.cpp | // C++ program Miller-Rabin Primality test
#include <iostream>
#include <vector>
#include <functional>
// Part of Cosmos by OpenGenus Foundation
// Utility function to do modular exponentiation.
// It returns (x^y) % p
int power(int x, unsigned int y, int p)
{
int res = 1; // Initialize result
x = x % p... |
code/mathematical_algorithms/src/primality_tests/miller_rabin_primality_test/miller_rabin_primality_test.java | import java.util.Random;
import java.lang.Math;
//Miller-Rabin primality test
//
//n: Tested number
//k: Number of iterations
//preconditions: n must be an odd number > 3
public class MillerRabinPrimalityTest {
public static boolean test(int n,int k){
int[] result = factors(n-1);
int r = result[0];
int d = r... |
code/mathematical_algorithms/src/primality_tests/miller_rabin_primality_test/miller_rabin_primality_test.py | import random
def check(a, s, d, n):
x = pow(a, d, n)
if x == 1:
return True
for i in range(s - 1):
if x == n - 1:
return True
x = pow(x, 2, n)
return x == n - 1
def isPrime(n, k=10):
if n == 2:
return True
if not n & 1:
return False
s... |
code/mathematical_algorithms/src/primality_tests/solovay_strassen_primality_test/solovay_strassen_primality_test.cpp | // C++ program to implement Solovay-Strassen
// Primality Test
#include <iostream>
using namespace std;
// modulo function to perform binary exponentiation
long long modulo(long long base, long long exponent,
long long mod)
{
long long x = 1;
long long y = base;
while (exponent > 0)
{
... |
code/mathematical_algorithms/src/prime_factors/prime_factors.c | #include <stdio.h>
typedef int bool;
#define true 1
#define false 0
int main()
{
int num;
bool isPrime;
printf("Enter the number whose factors you want to know : ");
scanf("%d",&num);
int factor;
printf("Factors of %d are \n",num);
while(num>1)
{
for(int i=2; i<=num; i++)
... |
code/mathematical_algorithms/src/prime_factors/prime_factors.cpp | // Part of Cosmos by OpenGenus Foundation
#include <stdio.h>
void prime_factors(int);
int main()
{
int n;
scanf("%d", &n);
prime_factors(n);
return 0;
}
void prime_factors(int n)
{
for (int d = 2; d * d <= n; d++) // take all divisors till sqrt(n)
{
if (n % d == 0)
printf("%d... |
code/mathematical_algorithms/src/prime_factors/prime_factors.go | // Part of Cosmos by OpenGenus Foundation
package main
import (
"fmt"
)
func prime_factors(target int) {
n := target
ans := []int{}
for d := 2; d*d <= n; d++ {
if n%d == 0 {
ans = append(ans, d)
for n%d == 0 {
n /= d
}
}
}
if n > 1 {
ans = append(ans, n)
}
fmt.Printf("The prime factors of ... |
code/mathematical_algorithms/src/prime_factors/prime_factors.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.*;
public class PrimeFactors {
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
... |
code/mathematical_algorithms/src/prime_factors/prime_factors.py | # Part of Cosmos by OpenGenus Foundation
Integer = int(input("Enter an Number : "))
absInteger = abs(Integer)
num = 1
prime_num = []
if absInteger > 0:
while num <= absInteger:
x = 0
if absInteger % num == 0:
y = 1
while y <= num:
if num % y == 0:
... |
code/mathematical_algorithms/src/prime_factors/sum_of_prime_factors.c | // A C program to find the sum of all the primes factors of given number .
#include <stdio.h>
#include <stdlib.h>
int main(){
unsigned long long int i,j,sum=0;
int *primes,num;
int z = 1;
printf("Enter the Number:");
scanf("%d",&num);
primes = malloc(sizeof(int) * num);
for (i = 2;i <= num... |
code/mathematical_algorithms/src/prime_factors/sum_of_primes.cpp | // A C++ program to find the sum of all the primes not greater than given N.
// Constraints: 1<=N<=10^6
// Constraints : 1<=t<=10^6
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
typedef long long int ll;
using namespace std;
int a[1000005] = {0}; ll b[1000005] = {0};
void sieve(int n)
{
ll s = 0;... |
code/mathematical_algorithms/src/prime_numbers_of_n/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/prime_numbers_of_n/prime_numbers_of_n.c | # include <stdio.h>
# include <stdlib.h>
# include <math.h>
int*
primeFactors(int number)
{
int* prime_factors = (int *)malloc(100 * sizeof(int));
int i, j = -1;
while (number % 2 == 0) {
++j;
prime_factors[j] = 2;
number = number / 2;
}
for (i = 3; i <= sqrt(number); i = i... |
code/mathematical_algorithms/src/prime_numbers_of_n/prime_numbers_of_n.cpp | #include <iostream>
#include <vector>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
#define N 10e7
vector<int> a(N + 1, 0);
void make_seive()
{
for (int i = 2; i < N; i++)
a[i] = i;
for (int i = 4; i < N; i += 2)
a[i] = 2;
for (int i = 2; i * i < N; i++)
if (a[i]... |
code/mathematical_algorithms/src/prime_numbers_of_n/prime_numbers_of_n.js | function primeFactors(number) {
let factors = [];
let limit = parseInt(Math.sqrt(number)); // used parseInt to avoid floating digit :D
while (number % 2 == 0) {
factors.push(2);
number = number / 2;
}
for (let i = 3; i <= limit; i += 2) {
while (number % i == 0) {
factors.push(i);
num... |
code/mathematical_algorithms/src/prime_numbers_of_n/prime_numbers_of_n.py | # Pollard-Rho-Brent Integer factorisation
# Complexity: O(n^(1/4) * log2(n))
# Output is list of primes factors & exponents.
# Example, N = 180 gives : [[2, 2], [3, 2], [5, 1]]
import random
from queue import Queue
def gcd(a, b):
while b:
a, b = b, a % b
return a
def expo(a, b):
x, y = 1, a
... |
code/mathematical_algorithms/src/pythagorean_triplet/pythagorean_triplet.cpp | // A Pythagorean triplet is a set of three natural numbers, a<b<c, for which a^2 + b^2 = c^2
// Given N, Check if there exists any Pythagorean triplet for which a+b+c=N
//Find maximum possible value of abc among all such Pythagorean triplets, If there is no such Pythagorean triplet print -1.
#include <iostream>
usin... |
code/mathematical_algorithms/src/pythagorean_triplet/pythagorean_triplet.py | """
A Pythagorean triplet is a set of three natural numbers, a<b<c, for which a^2 + b^2 = c^2
Given N, Check if there exists any Pythagorean triplet for which a+b+c=N
Find maximum possible value of abc among all such Pythagorean triplets, If there is no such Pythagorean triplet print -1.
"""
N = int(input())
arr = [1,... |
code/mathematical_algorithms/src/replace_0_with_5/0_to_5_efficent.cpp | #include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
long long int input()
{
char c;
long long int num = 0, neg = 1;
c = getchar();
if (c == '-')
{
neg = -1;
c = getchar();
}
while (c != '\n')
{
if (c == ' ')
return num * ... |
code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.c | // Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
int convert0To5Rec(int num)
{
if (num == 0)
return 0;
int digit = num % 10;
if (digit == 0)
digit = 5;
return convert0To5Rec(num/10) * 10 + digit;
}
int convert0To5(int num)
{
if (num == 0)
return 5;
else... |
code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.cpp | #include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
int main()
{
int n; cin >> n;
int a = 1;
while (n / a >= 1)
{
a = a * 10;
int temp = n % a - n % (a / 10);
temp = temp / (a / 10);
int temp2;
if (temp == 0)
{
... |
code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.cs | using System;
namespace Replace
{
public class Program
{
private static string replace(string number)
{
string N = "";
foreach (char n in number)
{
if (n == '0')
{
N += '5';
}
... |
code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
func zeroToFive(input int) int {
div := 1
ans := 0
for (input / div) > 0 {
tmp := (input / div) % 10
if tmp == 0 {
ans = 5*div + ans
} else {
ans = tmp*div + ans
}
div *= 10
}
return ans
}
func main() {
fmt.Printf("Change %d... |
code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.java | // Part of Cosmos by OpenGenus Foundation
import java.util.ArrayList;
public class Main {
static ArrayList<Integer> array = new ArrayList<>();
private static void replase(int num) {
while (num > 0) {
int k = num % 10;
array.add(k);
num = num / 10;
}
... |
code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.js | const Readline = require("readline");
const rl = Readline.createInterface({
input: process.stdin,
output: process.stdout
});
const replace0with5 = function replace0with5(number) {
return number.replace(new RegExp("0", "g"), 5);
};
rl.question("Enter a number: ", number => {
console.log(replace0with5(number))... |
code/mathematical_algorithms/src/replace_0_with_5/replace_0_with_5.py | # Part of Cosmos by OpenGenus Foundation
def replace_0_5_iterative(user_input):
modified = []
for i in user_input:
if i == "0":
modified.append("5")
else:
modified.append(i)
return "".join(modified)
def replace_0_5_pythonic(user_input):
return user_input.repla... |
code/mathematical_algorithms/src/reverse_factorial/README.md | # Reverse Factorial
It is inverse of factorial function.
When a number is given, we find a number such that factorial of that number is the given number.
|
code/mathematical_algorithms/src/reverse_factorial/reverse_factorial.c | #include <stdio.h>
void
reverse_factorial(long long int factorial)
{
long long int n = 1,m = 0;
while (m < 100) {
m += 1;
n *= m;
if (factorial == n) {
printf("%lli is %lli!\n",factorial,m);
break;
}
else if (m == 100)
printf("%lli is not a factorial product of any integer\n",factorial);
}
}
int... |
code/mathematical_algorithms/src/reverse_factorial/reverse_factorial.go | /*
* Part of Cosmos by OpenGenus Foundation
*/
package main
/*
Excepted outpout
720 is 6!
120 is 5!
24 is 4!
362880 is 9!
12345 isn't a factorial number
*/
import "fmt"
func reverseFactorial(target int) {
divisor, num := 2, target
for 0 == num%divisor {
num /= divisor
divisor++
}
if num == 1 {
fmt.Prin... |
code/mathematical_algorithms/src/reverse_factorial/reverse_factorial.java | // Part of Cosmos by OpenGenus Foundation
public static String reverseFactorial(int n) {
int number = n;
int divisor = 2;
while (number % divisor == 0) {
number /= divisor;
divisor++;
}
return String.format("%d = ", n) + ((divisor % number == 0) ? String.format("%d!", divisor - 1) : ... |
code/mathematical_algorithms/src/reverse_factorial/reverse_factorial.js | /*
* Part of Cosmos by OpenGenus Foundation
*/
function unfactorial(num) {
var d = 1;
while (num > 1 && Math.round(num) === num) {
d += 1;
num /= d;
}
if (num === 1) return d + "!";
else return "NONE";
}
|
code/mathematical_algorithms/src/reverse_factorial/reverse_factorial.py | # Part of Cosmos by OpenGenus Foundation
def reversefactorial(factorial):
n = 1
m = 0
notfound = True
while m < 100:
m += 1
n *= m
if factorial == n:
print(str(factorial) + " is " + str(m) + "!")
notfound = False
break
elif m == 100:
... |
code/mathematical_algorithms/src/reverse_factorial/reverse_factorial.rb | def inverse_factorial(num)
num = num.to_f
i = 2.0
j = 0
while i <= num
num /= i
j = i if num == 1
i += 1
end
j
end
num = 362_880
if inverse_factorial(num) > 0
puts inverse_factorial(num).to_s
else
puts 'No INVERSE FACTORIAL'
end
|
code/mathematical_algorithms/src/reverse_number/reverse_a_number.c | #include<stdio.h>
int main()
{
int a,b=0; //variable to get number
printf("enter a value to be reversed");
scanf("%d",&a);
while(a>0)
{
b=b*10+a%10;
a=a/10;
}
printf("%d is reverse number");
return 0;
}
|
code/mathematical_algorithms/src/reverse_number/reverse_number.c | #include <stdio.h>
int reverseNumber(int n)
{
int ans = 0;
while (n != 0)
{
ans *= 10;
ans += n % 10;
n /= 10;
}
return ans;
}
int main()
{
int n;
printf("Enter a number to reverse : ");
scanf("%d" , &n);
printf("Reverse of %d is %d" , n , reverseNumber(n));
return 0;
}
|
code/mathematical_algorithms/src/reverse_number/reverse_number.cpp | #include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
int reverse_number(int n)
{
int ans = 0;
while (n != 0)
{
ans *= 10;
ans += n % 10;
n /= 10;
}
return ans;
}
int main()
{
int n;
cin >> n;
cout << reverse_number(n);
return 0... |
code/mathematical_algorithms/src/reverse_number/reverse_number.cs | using System;
namespace reverse_number
{
class Program
{
static void Main(string[] args)
{
var num = 123456789;
Console.WriteLine("reverse of {0} is {1}", num, ReverseNumber(num));
}
static ... |
code/mathematical_algorithms/src/reverse_number/reverse_number.go | package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func main() {
num := 123456789
fmt.Println("reverse of", num, "is", reverseNumber(num))
}
func reverseNumber(n int) int {
splits := strings.Split(strconv.Itoa(n), "")
sort.Sort(sort.Reverse(sort.StringSlice(splits)))
i, _ := strconv.Atoi(strings.Join(... |
code/mathematical_algorithms/src/reverse_number/reverse_number.hs | reverseInt :: Integer -> Integer
reverseInt x | x < 0 = 0 - (read . reverse . tail . show $ x)
| otherwise = read . reverse . show $ x
|
code/mathematical_algorithms/src/reverse_number/reverse_number.java | import java.util.*;
public class Reverse
{
public static Scanner scr=new Scanner(System.in); //Scanner object to take input
public static void main(String[] args) //Main function
{
int num;
System.out.print("Enter a number: ");
num=scr.nextInt(); //Number input
System.out.println();
int reverse=0;... |
code/mathematical_algorithms/src/reverse_number/reverse_number.js | function reverse_number(value) {
let reversed = String(value)
.split("")
.reverse()
.join("");
return Number(reversed);
}
console.log(reverse_number(123456789)); // 987654321
console.log(reverse_number(12.34)); // 43.21
|
code/mathematical_algorithms/src/reverse_number/reverse_number.php | <?php
function reverse_number($numbers) {
$string = (string) $numbers;
$result = "";
$length = strlen($string);
for ($i = $length - 1; $i >= 0; $i--) {
$result .= $string[$i];
}
return $result ;
}
echo reverse_number(123456789);
|
code/mathematical_algorithms/src/reverse_number/reverse_number.py | def reverse_number(n):
return int(str(n)[::-1])
if __name__ == "__main__":
print(reverse_number(123456789))
|
code/mathematical_algorithms/src/reverse_number/reverse_number.rb | ''"
Author: ryanml
Path of Cosmos by OpenGenus Foundation
"''
class NumReverse
def reverse(n)
n.to_s.chars.reverse.join.to_i
end
end
def tests
reverser = NumReverse.new
puts reverser.reverse(2425)
puts reverser.reverse(9999)
puts reverser.reverse(5)
puts reverser.reverse(123_456)
end
tests
|
code/mathematical_algorithms/src/reverse_number/reverse_number.swift | //
// reversed_number.swift
// test
//
// Created by Kajornsak Peerapathananont on 10/14/2560 BE.
// Copyright © 2560 Kajornsak Peerapathananont. All rights reserved.
//
import Foundation
func reversed_number(number : Int) -> Int {
return Int(String("\(number)".reversed()))!
}
|
code/mathematical_algorithms/src/reverse_number/reverse_number_iterative.c |
#include <stdio.h>;
/* iterative function to reverse digits of num*/
int reversDigits(int num)
{
int rev_num = 0;
while (num != 0)
{
rev_num = (rev_num)*10 + num % 10;
num /= 10;
}
return rev_num;
}
/*Driver program to test reversDigits*/
int main()
{
int num;
printf("Ente... |
code/mathematical_algorithms/src/reverse_number/reverse_number_recursion.java | import java.util.*;
/*
@author Kanika Saini (https://github.com/kanikasaini)
*/
class ReverseIntUsingRecursion
{
public static void main(String[] args) throws Exception
{
int reversed= reverse(1234);
System.out.println(sum); //prints 4321
}
static int sum=0;
public static int reverse(int num)
{
if (num!=0)
{
in... |
code/mathematical_algorithms/src/russian_peasant_multiplication/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/russian_peasant_multiplication/russian_peasant_multiplication.c | #include <stdio.h>
unsigned int
russianPeasant(unsigned int a, unsigned int b)
{
int res = 0;
while (b > 0) {
if (b & 1)
res += a;
a = a << 1;
b = b >> 1;
}
return (res);
}
int
main()
{
printf("%u\n", russianPeasant(18, 1));
printf("%u\n", russianPeasant... |
code/mathematical_algorithms/src/russian_peasant_multiplication/russian_peasant_multiplication.cpp | #include <iostream>
using namespace std;
unsigned int russianPeasant(unsigned int a, unsigned int b)
{
int res = 0; // initialize result
while (b > 0)
{
if (b & 1)
res = res + a;
a = a << 1;
b = b >> 1;
}
return res;
}
int main()
{
cout << russianPeasant(1... |
code/mathematical_algorithms/src/russian_peasant_multiplication/russian_peasant_multiplication.cs | using System;
namespace russian_peasant
{
static class russ_peasant
{
static public int multiply(int a, int b)
{
int res = 0;
while (b > 0)
{
if (b % 2 == 1)
{
res += a;
}
a ... |
code/mathematical_algorithms/src/russian_peasant_multiplication/russian_peasant_multiplication.go | package main
import "fmt"
func russianPeasant(a, b int) int {
// Init result
res := 0
//While second munber doesn't become 1
for b > 0 {
// If second number is odd, add first number to result
if (b & 1) != 0 {
res += a
}
// Double the first number
a = a << 1
// Halve the second number
b = b >> 1... |
code/mathematical_algorithms/src/russian_peasant_multiplication/russian_peasant_multiplication.js | function russianPeasant(a, b) {
let res = 0;
while (b > 0) {
if (b & 1) {
res = res + a;
}
a = a << 1;
b = b >>> 1;
}
return res;
}
console.log(russianPeasant(18, 1), russianPeasant(2, 4));
|
code/mathematical_algorithms/src/russian_peasant_multiplication/russian_peasant_multiplication.php | <?php
function russianPeasant($a,$b){
$res = 0;
while ($a >= 1){
if($a%2 !== 0 || $b%2 !== 0){
$res = $res + $b;
}
$a = $a/2;
$b = $b*2;
}
return $res;
}
echo russianPeasant(6,4); |
code/mathematical_algorithms/src/russian_peasant_multiplication/russian_peasant_multiplication.py | # Part of Cosmos by OpenGenus Foundation
def russian_peasant(a, b):
res = 0
while b > 0:
if b % 2 == 1:
res += a
a *= 2
b //= 2
return res
print(russian_peasant(18, 24))
print(russian_peasant(20, 12))
|
code/mathematical_algorithms/src/russian_peasant_multiplication/russian_peasant_multiplication.rs | fn russian_peasant(mut a: u32, mut b: u32) -> u32 {
let mut res = 0;
while b > 0 {
if (b & 1) != 0 {
res += a;
}
a = a << 1;
b = b >> 1;
}
res
}
fn main() {
println!("{}", russian_peasant(18, 24));
println!("{}", russian_peasant(20, 12));
} |
code/mathematical_algorithms/src/segmented_sieve_of_eratosthenes/segmented_sieve_of_eratosthenes.cpp | //Code Copyright: Manish Kumar, E&C, IIT Roorkee
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <cmath>
#include <cstring>
#include <vector>
using namespace std;
vector<int> Prime; //contains prime numbers uptop segMax
void segmentedSieve()
{
#define segMax 1000000 //till point you want to... |
code/mathematical_algorithms/src/shuffle_array/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/shuffle_array/shuffle_array.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
void
swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void
shuffle_array(int arr[], int n)
{
srand(time(NULL));
int i;
for (i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
swap(&arr[i], &arr[j]);
}
for (i = 0; i < n; i++)
printf("%... |
code/mathematical_algorithms/src/shuffle_array/shuffle_array.cpp | #include <iostream>
#include <algorithm>
#include <random>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
int main()
{
int A[] = { 1, 2, 3, 4, 5, 6 };
shuffle(A, A + 6, default_random_engine(time(NULL)));
for (auto a : A)
cout << a << " ";
return 0;
}
|
code/mathematical_algorithms/src/shuffle_array/shuffle_array.js | /* Part of Cosmos by OpenGenus Foundation */
//shuffle_array - Randomly shuffle an array
//Note: This method changes the original array.
function shuffle_array(arr) {
if (!Array.isArray(arr)) {
//If not an array return arr
return arr;
}
return arr.sort((a, b) => {
return Math.random() - 0.5;
});
}... |
code/mathematical_algorithms/src/shuffle_array/shuffle_array.rb | # Part of Cosmos by OpenGenus Foundation
class Shuffler
# This shuffle uses Fisher-Yates shuffle algorithm
def self.arr!(array)
len = array.length
while len > 0
len -= 1
i = rand(len)
array[i], array[len] = array[len], array[i]
end
end
def self.arr(array)
a = array.clone
a... |
code/mathematical_algorithms/src/sieve_of_atkin/sieve_of_atkin.c | #include <stdio.h>
#include <math.h>
int main() {
int limit;
int wlimit;
int i, j, k, x, y, z;
unsigned char *sieb;
printf("Insert a number to which are primes are calculated here: ");
scanf("%d", &limit);
sieb = (unsigned char *) calloc(limit, sizeof(unsigned char));
wlimit = sq... |
code/mathematical_algorithms/src/sieve_of_atkin/sieve_of_atkin.cpp | // C++ program for implementation of Sieve of Atkin
#include <bits/stdc++.h>
using namespace std;
void SieveOfAtkin(int limit)
{
// 2 and 3 are known to be prime
if (limit > 2)
cout << 2 << " ";
if (limit > 3)
cout << 3 << " ";
// Initialise the sieve array with false values
bool s... |
code/mathematical_algorithms/src/sieve_of_atkin/sieve_of_atkin.java | /**
** Java Program to implement Sieve Of Atkin Prime generation
**/
import java.util.Scanner;
/** Class SieveOfAtkin **/
public class SieveOfAtkin
{
/** Function to calculate all primes less than n **/
private boolean[] calcPrimes(int limit)
{
/** initialize the sieve **/
boolean[] p... |
code/mathematical_algorithms/src/sieve_of_atkin/sieve_of_atkin.py | # Part of Cosmos by OpenGenus Foundation
from math import sqrt, ceil
def atkin_sieve(n):
# Include 2,3,5 in initial results
if n >= 5:
result = [2, 3, 5]
elif n >= 3 and n < 5:
result = [2, 3]
elif n == 2:
result = [2]
else:
result = []
# Initialize sieve; all... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.