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"
<< "\nUsage: newton-raphson INITIAL_GUESS ERROR_LIMIT MAX_ITERATIONS\n"
<< "\tINITIAL_GUESS - The initial guess (x0). A number.\n"
<< "\tERROR_LIMIT - The stopping condition. A positive number.\n"
<< "\tMAX_ITERATIONS - The maximum number of allowed iterations. A positive number.\n"
<< "\n\tExample: newton_raphson 1 0.001 1000" << std::endl;
exit(1);
}
int main(int argc, char* argv[])
{
if (argc != 4)
helpAndExit();
float x0, allowedError;
int maxIterations;
try {
x0 = std::stof(std::string(argv[1]));
allowedError = std::stof(std::string(argv[2]));
maxIterations = std::stoi(std::string(argv[3]));
if (allowedError < 0.0f || maxIterations < 0)
throw std::domain_error("Error limit and number of iterations must be positive numbers!");
} catch (std::exception& e)
{
std::cout << e.what() << "\n" << std::endl;
helpAndExit();
}
auto f = [](const float x)
{
return x * std::log10(x) - 1.2;
};
auto df = [](const float x)
{
return std::log10(x) + 0.43429;
};
for (auto i = 1; i < maxIterations; i++)
{
const auto error = f(x0) / df(x0);
if (std::fabs(error) < allowedError)
{
std::cout << "Conversion reached after: " << i << " iterations. Solution: " << x0 <<
std::endl;
return 0;
}
x0 = x0 - error;
}
std::cout << "Convergence not reached after " << maxIterations << " iterations" << std::endl;
return 0;
}
|
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 = abs(df($interN)) >= abs(df($interM)) ? $interN : $interM;
return $first;
}
function getXn($x){
return ($x - (f($x)/df($x)));
}
for ($i=0; $i < $maxIteration; $i++) {
$xn = $i === 0 ? firstIterationValue($intervalOne,$intervalTwo) : getXn($xn);
$dxn = df($xn);
echo "I: {$i} | N: {$xn} <br>";
if($i == $maxIteration-1){
echo "Max Iteration Reached";
}else if($xn <= $precision){
echo "Precision reached";
break;
}
} |
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";
return;
}
int x = num[i - 1], small = i;
for (j = i + 1; j < n; ++j)
if (num[j] > x && num[j] < num[small])
small = j;
std::swap(num[i - 1], num[small]);
std::sort(num + i, num + n);
std::cout << num;
}
int main()
{
using namespace std;
char num[20];
cin >> num;
int n = strlen(num);
nextgr(num, n);
cout << endl;
return 0;
}
|
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_split($num));
$cnt = count($arr);
for ($i = $cnt - 1; $i > 0; $i--) {
if ($arr[$i] > $arr[$i - 1]) {
break;
}
}
if ($i === 0) {
return false;
}
$i--;
$i_val = $arr[$i];
$smallest = 9;
$smallest_idx = 0;
for ($j = $i + 1; $j < $cnt; $j++) {
if ($arr[$j] > $i_val && $arr[$j] <= $smallest) {
$smallest = $arr[$j];
$smallest_idx = $j;
}
}
$arr[$smallest_idx] = $arr[$i];
$arr[$i] = $smallest;
$tail = array_slice($arr, $i + 1);
sort($tail);
array_splice($arr, $i + 1, count($tail), $tail);
return (int)implode('', $arr);
}
echo "next larger number\n";
$test_data = [
[1, false],
[15, 51],
[51, false],
[697, 769],
[796, 967],
[799, 979],
[5674, 5746],
[1234554321, 1235123445],
[9876556789, 9876556798],
[98765567890, 98765567908],
[12345543214, 12345543241],
[111110, false],
[100001, 100010],
[191919, 191991],
[919191, 919911],
[54321, false],
[14321, 21134],
[99999, false],
];
foreach ($test_data as $test_case) {
$input = $test_case[0];
$expected = $test_case[1];
$result = next_larger_number($input);
printf(
" input %d, expected %s, got %s: %s\n",
$input,
var_export($expected, true),
var_export($result, true),
($expected === $result) ? 'OK' : 'FAIL'
);
}
|
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 most digit and find the first
# digit that is smaller than the digit next to it
for i in range(n - 1, 0, -1):
if number[i] > number[i - 1]:
break
# If no such digit found,then all numbers are in
# descending order, no greater number is possible
if i == 0:
print("Next number not possible")
return
# Find the smallest digit on the right side of
# (i-1)'th digit that is greater than number[i-1]
x = number[i - 1]
smallest = i
for j in range(i + 1, n):
if number[j] > x and number[j] < number[smallest]:
smallest = j
# Swapping the above found smallest digit with (i-1)'th
number[smallest], number[i - 1] = number[i - 1], number[smallest]
# X is the final number, in integer datatype
x = 0
# Converting list upto i-1 into number
for j in range(i):
x = x * 10 + number[j]
# Sort the digits after i-1 in ascending order
number = sorted(number[i:])
# converting the remaining sorted digits into number
for j in range(n - i):
x = x * 10 + number[j]
print("Next number with set of digits is", x)
digits = input("Enter the Number")
# converting into integer array,
# number becomes [5,3,4,9,7,6]
number = list(map(int, digits))
findNext(number, len(digits))
|
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 collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
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", &number);
printf("Enter base (min:2,max:10): ");
scanf("%d", &base);
if(base < 2 || base > 10){
printf("%d is not in [2,10] range.\n", base);
return 1;
}
if(check_number(number, base)){
if(is_pandigital(number, base)){
printf("%lld is a pandigital number in base %d\n", number, base);
}else{
printf("%lld is not a pandigital number in base %d\n", number, base);
}
if(is_zeroless_pandigital(number, base)){
printf("%lld is a zeroless pandigital number in base %d\n", number, base);
}else{
printf("%lld is not a zeroless pandigital number in base %d\n", number, base);
}
}else{
printf("%lld is not a valid number in base %d\n", number, base);
}
return 0;
}
/**
* this function checks if a number is pandigital in the given base
* @param number number to be checked
* @param base base to be checked
* @return true if the number is pandigital in the given base, false otherwise
*/
int is_pandigital(long long number, int base){
/* define an array to hold count of all digits */
int digits[10], i;
memset(digits, 0, sizeof(int)*10);
/* for every digit in number, increment count by one */
while(number > 0){
int digit = number % 10;
++digits[digit];
number /= 10;
}
/* iterate over digits to see if there's an empty one, if so return false */
for(i = 0; i < base; ++i)
if(digits[i] == 0)
return 0;
/* if no empty digit found, return true */
return 1;
}
/**
* this function checks if a number is zeroless pandigital in the given base
* @param number number to be checked
* @param base base to be checked
* @return true if the number is a zeroless pandigital in the given base, false otherwise
*/
int is_zeroless_pandigital(long long number, int base){
/* define an array to hold count of all digits */
int digits[10], i;
memset(digits, 0, sizeof(int)*10);
/* for every digit in number, increment count by one */
while(number > 0){
int digit = number % 10;
if(digit == 0) return 0;
++digits[digit];
number /= 10;
}
/* iterate over digits to see if there's an empty one, if so return false */
for(i = 1; i < base; ++i)
if(digits[i] == 0)
return 0;
/* if no empty digit found, return true */
return 1;
}
/* This function checks if given number is valid in the given base */
int check_number(long long number, int base){
while(number > 0){
int digit = number % 10;
if(digit > base - 1) return 0;
number /= 10;
}
return 1;
}
|
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 = ((1 << 9) - 1) - (1 << (dgt - 1))
digits &= dgt_map
num /= 10
end
digits == 0
end
puts is_pandigital(185_239)
puts is_pandigital(9_483_271_065)
puts is_pandigital(1_223_334_444_555_556_666_667_777_777_888_888_889_999_999_990)
puts is_zeroless_pandigital(185_239)
puts is_zeroless_pandigital(9_483_271_065)
puts is_zeroless_pandigital(948_327_165)
|
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 entries are treated as a 0).
## Example
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
## Further Reading
[Wikipedia - Pascal's Triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle)
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
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;j<=i;j++){
printf("%lli ",a[i][j]);
}
printf("\n");
}
return (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)
{
pascal[i][0] = pascal[i][i] = 1;
for (int j = 1; j < i; ++j)
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
return pascal;
}
int main()
{
int n;
scanf("%d", &n);
vvi pascal = pascal_triangle(n);
for (int i = 0; i <= n; ++i)
for (int j = 0; j <= i; ++j)
printf("%2d%c", pascal[i][j], " \n"[j == i]);
return 0;
}
|
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) / i
}
return prod
}
func pascalTriangle(rows int) [][]int {
matrix := make([][]int, rows+1, rows+1)
for y := 0; y <= rows; y++ {
matrix[y] = make([]int, y+1, y+1)
}
for y := 0; y <= rows; y++ {
matrix[y][0] = 1
matrix[y][y] = 1
}
for y := 2; y <= rows; y++ {
for x := 1; x <= y - 1; x++ {
matrix[y][x] = matrix[y-1][x-1] + matrix[y-1][x]
}
}
return matrix
}
func main() {
fmt.Println("Combinatorics test: ")
n := 10
for k := 0; k <= n; k++ {
fmt.Print("C(", n, ", ", k, ") = ", combination(n, k), "\n")
}
fmt.Print("\nPascal triangle up to N = 10:\n")
matrix := pascalTriangle(10)
for i := 0; i <= 10; i++ {
for j := 0; j <= i; j++ {
fmt.Print(matrix[i][j], " ")
}
fmt.Print("\n")
}
} |
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 < i; ++f) {
matrix[i][f] = matrix[i - 1][f - 1] + matrix[i - 1][f];
}
}
return matrix;
}
public static void main(String[] args) {
System.out.print("Enter number of rows: ");
Scanner valEnter = new Scanner(System.in);
int value = valEnter.nextInt();
value++;
Integer[][] mas = PascalTriangle(value);
//Beautiful output
for (int q = 0; q < value; q++) {
for (int k = 0; k <= q; k++) {
System.out.format("%d", mas[q][k]);
System.out.print(" ");
}
System.out.println();
}
}
}
|
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 range(x):
return combination(x, y)
def pascals_triangle(rows):
result = [] # need something to collect our results in
# count = 0 # avoidable! better to use a for loop,
# while count <= rows: # can avoid initializing and incrementing
for count in range(rows): # start at 0, up to but not including rows number.
# this is really where you went wrong:
row = [] # need a row element to collect the row in
for element in range(count + 1):
# putting this in a list doesn't do anything.
# [pascals_tri_formula.append(combination(count, element))]
row.append(combination(count, element))
result.append(row)
# count += 1 # avoidable
return result
# now we can print a result:
for row in pascals_triangle(inp):
print(row)
|
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 is 28 = 1 + 2 + 4 + 7 + 14.
This is followed by the perfect numbers 496 and 8128
To run JavaScript code: node perfect-number.js
To run Java code:
1. javac PerfectNumber.java
1. jar -cvfe PerfectNumber.jar PerfectNumber PerfectNumber.class
1. java -jar PerfectNumber.jar
Collaborative effort by [OpenGenus](https://github.com/OpenGenus)
|
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");
return 0;
}
|
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
cout << num << " IS NOT A PERFECT NUMBER\n";
return 0;
}
|
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 = 6; i < number; i++) {
if (isPerfect(i)) {
System.out.println(i + " is a perfect number.");
hasPerfect = true;
}
}
if (!hasPerfect) {
System.out.println("No perfect numbers found.");
}
}
private final static boolean isPerfect(final int number) {
int sum = 0;
for (int i = 1; i < number - 1; i++) {
int rem = number % i;
if (rem == 0) {
sum += i;
}
}
return sum == number;
}
}
|
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 + " is a perfect number.");
hasPerfect = true;
}
}
if (!hasPerfect) {
console.log("No perfect numbers found.");
}
rl.close();
});
function isPerfect(number) {
let sum = 0;
for (let i = 1; i < number - 1; i++) {
let rem = number % i;
if (rem === 0) {
sum += i;
}
}
return sum === number;
}
|
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 is a perfect number.', $number) : sprintf('%d is not a perfect number.', $number);
|
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() {
for i in 1..100 {
println!("{} is perfect: {}", i, is_perfect(i));
}
println!("{} is perfect: {}", 496, is_perfect(496));
}
|
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_check)
{
int sum = 0, i; // Class level variables
for (i = 1; i < p_num_to_check; i++) // Loop from [1, num) TODO: Improve this
if (p_num_to_check % i == 0)
sum += i;
return sum == p_num_to_check;
}
|
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]);
permutation(a, i + 1);
swap(a[i], a[j]);
}
}
int main()
{
string a;
cout << "Enter any string : ";
cin >> a;
permutation(a);
set<string>::iterator i;
for (i = s.begin(); i != s.end(); i++)
cout << *i << endl;
return 0;
}
|
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 = 0
while rand_num > 0: # Uses the inversion method to generate values
rand_num -= (
mean ** count * exp(-mean) / factorial(count)
) # Subtract P(X=count)
count += 1
sample.append(count - 1)
return sample
|
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<< power(base,p) <<"\n";
}
return 0;
} |
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)) %mod;
}
int main(){
int base,p,mod;
while(cin>>base>>p>>mod){
cout<< power(base,p,mod) <<"\n";
}
return 0;
} |
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 technique
long long expMod(long long base, long long exp, long long c) {
long long res=1;
while(exp>0) {
if(exp%2==1) res=(res*base)%c;
base=(base*base)%c;
exp/=2;
}
return res%c;
}
//function to run fermat's test
bool fermatTest(long int p, int k) {
int i;
if (p==1)
return false;
for (i=0; i<k; i++) {
long long a = rand() % (p - 1) + 1;
if (expMod(a, p - 1, p) != 1)
return false;
}
return true;
}
/**
* driver function taking number to be tested
* and number of iterations as inputs
**/
int main(void) {
int i;
for(i = 15; i>1; i--){
if(fermatTest(i, ITERATIONS))
printf("%d is prime\n",i);
else
printf("%d is composite\n",i);
}
return 0;
}
|
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")
else:
print("Not 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; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// This function is called for all k trials. It returns
// false if n is composite and returns false if n is
// probably prime.
// d is an odd number such that d*2<sup>r</sup> = n-1
// for some r >= 1
bool miillerTest(int d, int n)
{
// Pick a random number in [2..n-2]
// Corner cases make sure that n > 4
int a = 2 + rand() % (n - 4);
// Compute a^d % n
int x = power(a, d, n);
if (x == 1 || x == n - 1)
return true;
// Keep squaring x while one of the following doesn't
// happen
// (i) d does not reach n-1
// (ii) (x^2) % n is not 1
// (iii) (x^2) % n is not n-1
while (d != n - 1)
{
x = (x * x) % n;
d *= 2;
if (x == 1)
return false;
if (x == n - 1)
return true;
}
// Return composite
return false;
}
// It returns false if n is composite and returns true if n
// is probably prime. k is an input parameter that determines
// accuracy level. Higher value of k indicates more accuracy.
bool isPrime(int n, int k)
{
// Border cases
if (n <= 1 || n == 4)
return false;
if (n <= 3)
return true;
// Find r such that n = 2^d * r + 1 for some r >= 1
int d = n - 1;
while (d % 2 == 0)
d /= 2;
// Iterate given number 'k' times
for (int i = 0; i < k; i++)
if (miillerTest(d, n) == false)
return false;
return true;
}
// Driver program
int main()
{
using namespace std;
int n, k = 4;
//Here k decides the number of iterations the number 'n' will undergo.
//Larger the value of k, more will be the accuracy of the output
//thus reducing its efficiency.
cout << "Enter the number to check: ";
cin >> n;
if (isPrime(n, k))
cout << n << " is prime.\n";
else
cout << n << " is not prime.\n";
return 0;
}
|
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 = result[1];
while(k != 0){
int power = 1; //Power declaration and initial assignment
boolean notPrime = false;
Random rand = new Random();
int randomNum = rand.nextInt(n-1) + 2;
int x = (int)Math.pow(randomNum,d) % n;
if(x == 1 || x == n-1){
notPrime = true;
}
while (power < r){
x = (int)Math.pow(randomNum,((int)Math.pow(2,power)*d)) % n;
if(x == n-1){
notPrime = true;
break;
}
power = power + 1;
}
k = k-1;
if(!notPrime){
return false;
}
}
return true;
}
public static int[] factors(int n){ //Write n as 2^s * d
int[] result = new int[2];
int r = 1;
while((n % (int)Math.pow(2,r) != 0) || (n / (int)Math.pow(2,r) % 2) == 0){
r = r+1;
}
result[0] = r;
result[1] = n / (int)Math.pow(2,r);
return result;
}
public static void main(String[] args){
boolean test = test(13,5);
System.out.println(test);
}
}
|
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 = 0
d = n - 1
while d % 2 == 0:
d >>= 1
s += 1
for i in range(k):
a = random.randint(2, n - 1)
if not check(a, s, d, n):
return False
return True
|
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)
{
if (exponent % 2 == 1)
x = (x * y) % mod;
y = (y * y) % mod;
exponent = exponent / 2;
}
return x % mod;
}
// To calculate Jacobian symbol of a given number
int calculateJacobian(long long a, long long n)
{
if (!a)
return 0; // (0/n) = 0
int ans = 1;
if (a < 0)
{
a = -a; // (a/n) = (-a/n)*(-1/n)
if (n % 4 == 3)
ans = -ans; // (-1/n) = -1 if n = 3 (mod 4)
}
if (a == 1)
return ans; // (1/n) = 1
while (a)
{
if (a < 0)
{
a = -a;// (a/n) = (-a/n)*(-1/n)
if (n % 4 == 3)
ans = -ans; // (-1/n) = -1 if n = 3 (mod 4)
}
while (a % 2 == 0)
{
a = a / 2;
if (n % 8 == 3 || n % 8 == 5)
ans = -ans;
}
swap(a, n);
if (a % 4 == 3 && n % 4 == 3)
ans = -ans;
a = a % n;
if (a > n / 2)
a = a - n;
}
if (n == 1)
return ans;
return 0;
}
// To perform the Solovay-Strassen Primality Test
bool solovoyStrassen(long long p, int iterations)
{
if (p < 2)
return false;
if (p != 2 && p % 2 == 0)
return false;
for (int i = 0; i < iterations; i++)
{
// Generate a random number a
long long a = rand() % (p - 1) + 1;
long long jacobian = (p + calculateJacobian(a, p)) % p;
long long mod = modulo(a, (p - 1) / 2, p);
if (!jacobian || mod != jacobian)
return false;
}
return true;
}
// Driver Code
int main()
{
int iterations = 50;
long long num1 = 15;
long long num2 = 13;
if (solovoyStrassen(num1, iterations))
printf("%lld is prime\n", num1);
else
printf("%lld is composite\n", num1);
if (solovoyStrassen(num2, iterations))
printf("%lld is prime\n", num2);
else
printf("%lld is composite\n", num2);
return 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++)
{
if(num%i==0)
{
isPrime = true;
for(int j=2; j<=i/2; j++)
{
if(i%j==0)
{
isPrime = false;
break;
}
}
if(isPrime==true)
{
printf("%d ", i);
num /= i;
}
}
}
}
printf("\n");
return 0;
}
|
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 ", d); //this is surely prime,if it weren't, an earlier divisor of it would've nuked it from n
while (n % d == 0)
n /= d;
//nuke the prime divisor from n
}
if (n > 1)
printf("%d", n);
//we nuked all prime divisors,so if n is not one,then it's prime
}
|
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 %d is %v\n", target, ans)
}
func main() {
var i int
fmt.Print("Enter number: ")
fmt.Scan(&i)
prime_factors(i)
}
|
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) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println("Primefactors of " + n);
List<Integer> al = primeFactors(n);
//remove duplicate
// if you want the duplicate remove the following 3 lines
Set<Integer> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);
for (Integer integer : al) {
System.out.println(integer);
}
}
}
|
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:
x = x + 1
y = y + 1
if x == 2:
prime_num.append(num)
num = num + 1
print("Your Input: " + str(Integer))
print("Prime Factors : " + str(prime_num))
elif absInteger == 0:
print("Your Input: 0")
print("Prime Factors : [0]")
else:
print("Please Input a number")
|
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; i++)
primes[i] = 1;
for (i = 2;i <= num; i++)
if (primes[i])
for (j = i;i * j <= num; j++)
primes[i * j] = 0;
printf("\nPrime numbers are: \n");
for (i = 2;i <= num; i++)
if (primes[i]&& num%i==0)
sum+=i;
printf("%lld\n", sum);
return 0;
}
|
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;
int i;
for (i = 2; i * i <= n; i++)
{
if (a[i] == 0)
{
s += i;
for (int j = 2 * i; j <= n; j += i)
a[j] = 1;
}
b[i] = s;
}
int j;
for (j = i; j <= n; j++)
{
if (a[j] == 0)
s += j;
b[j] = s;
}
}
int main()
{
sieve(1000000); // precomputing the summation of all primes upto n less than or equal to 10^6
int t;
cin >> t; // No. of test cases as input
while (t--)
{
int n;
cin >> n; // Given input number n
cout << b[n] << endl; // b[n] gives summation of all primes less than or equal to n.
}
}
|
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 + 2) {
while (number % i == 0) {
++j;
prime_factors[j] = i;
number = number / i;
}
}
if (number > 2) {
++j;
prime_factors[j] = number;
}
return (prime_factors);
}
int
main()
{
int number, i;
printf("Enter a Natural Number \n");
scanf("%d", &number);
int* result = primeFactors(number);
printf("Prime Factors of %d are:- \n", number);
for (i = 0; result[i] != 0; i++)
printf("%d ", result[i]);
printf("\n");
return (0);
}
|
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] == i)
for (int j = i * i; j < N; j += i) // j=i*i because for j=i*2,i*3,i*4,i*5....,i*(i-1) we already
// have a[j] = 2,3,4,5,6,7,......i-1 so that why we are starting
// from i=i*i
if (a[j] == j)
a[j] = i;
}
void print_prime_factors(int n)
{
while (n != 1)
{
cout << a[n] << " ";
n = n / a[n];
}
}
int main()
{
make_seive();
int n;
cin >> n;
print_prime_factors(n);
return 0;
}
|
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);
number = number / i;
}
}
if (number > 2) {
factors.push(number);
}
return factors;
}
// test cases
console.log(primeFactors(10)); // [2, 5]
console.log(primeFactors(100)); // [2, 2, 5, 5]
console.log(primeFactors(300)); // [2, 2, 3, 5, 5]
|
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
while b > 0:
if b & 1:
x = x * y
y = y * y
b >>= 1
return x
primes = [0] * 100000
def sieve():
primes[1] = 1
primes[2] = 2
j = 4
while j < 100000:
primes[j] = 2
j += 2
j = 3
while j < 100000:
if primes[j] == 0:
primes[j] = j
i = j * j
k = j << 1
while i < 100000:
primes[i] = j
i += k
j += 2
# Checks if p is prime or not.
def rabin_miller(p):
if p < 100000:
# Precomputation make checking for small numbers O(1).
return primes[p] == p
if p % 2 == 0:
return False
s = p - 1
while s % 2 == 0:
s >>= 1
for i in range(5):
a = random.randrange(p - 1) + 1
temp = s
mod = pow(a, temp, p)
while temp != p - 1 and mod != 1 and mod != p - 1:
mod = (mod * mod) % p
temp = temp * 2
if mod != p - 1 and temp % 2 == 0:
return False
return True
# Returns a prime factor of N.
def brent(N):
if N % 2 == 0:
return 2
if N < 100000:
return primes[N]
y, c, m = (
random.randint(1, N - 1),
random.randint(1, N - 1),
random.randint(1, N - 1),
)
g, r, q = 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = ((y * y) % N + c) % N
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = ((y * y) % N + c) % N
q = q * (abs(x - y)) % N
g = gcd(q, N)
k = k + m
r = r * 2
if g == N:
while True:
ys = ((ys * ys) % N + c) % N
g = gcd(abs(x - ys), N)
if g > 1:
break
return g
def factorise(n):
if n == 1:
return []
Q_1 = Queue()
Q_2 = []
Q_1.put(n)
while not Q_1.empty():
l = Q_1.get()
if rabin_miller(l):
Q_2.append(l)
continue
d = brent(l)
if d == l:
Q_1.put(l)
else:
Q_1.put(d)
Q_1.put(l // d)
return Q_2
if __name__ == "__main__":
sieve()
t = int(input()) # Denotes number of testcases.
for _ in range(t):
n = int(input())
L = factorise(n)
L.sort()
i = 0
factors = []
while i < len(L):
cnt = L.count(L[i])
factors.append([L[i], cnt])
i += cnt
print(factors)
|
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>
using namespace std;
#define opt std::ios_base::sync_with_stdio(false)
typedef long long int ll;
int main()
{
opt;
int t;
cin >> t;
while (t--)
{
double n;
ll m = 0;
cin >> n;
double a;
for (a = 1; a < n / 2; a++) // keeping a and n constant and using given two equations, we will get the value of b and c in terms of n and a
{ // from expression of b, we can see that a should be less than n/2
double b, c;
b = ((n * n) - 2 * a * n) / (2 * (n - a)); //solving the given 2 equations, we will get this expression of b
c = ((n - a) * (n - a) + (a * a)) / (2 * (n - a)); //solving the given 2 equations, we will get this expression of c
int p = int(b), q = int(c);
if (b == p && c == q && ((a * a + b * b) == (c * c)) )
m = max(m, ll(ll(a) * p * q));
}
(m != 0) ? cout << m << endl : cout << -1 << endl;
}
}
|
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,1,1]
for i in range(1,N):
for j in range(i+1, N):
if i + j > N:
break
for k in range(j+1, N):
if i + j + k > N:
break
if i*i + j*j == k*k and i + j + k == N:
if i*j*k > arr[0]*arr[1]*arr[2]:
arr = [i,j,k]
prod = arr[0]*arr[1]*arr[2]
if prod > 1:
print(f"{arr[0]}^2 + {arr[1]}^2 = {arr[2]}^2, Product = {prod}")
else:
print(-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 * neg;
if (c == '0')
c = '5';
num = num * 10 + (c - '0');
c = getchar();
}
return num * neg;
}
int main()
{
long long int number;
number = input();
cout << number << "\n";
}
|
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
return convert0To5Rec(num);
}
int main()
{
int num = 10120;
printf("%d", convert0To5(num));
return 0;
}
|
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)
{
temp2 = 5 * (a / 10);
n = n - temp + temp2;
}
}
cout << n << endl;
}
|
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';
}
else
{
N += n;
}
}
return N;
}
public static void Main()
{
Console.Write("enter a number : ");
string number = Console.ReadLine();
Console.WriteLine(replace(number));
}
}
}
|
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 to %d\n", 10203, zeroToFive(10203))
fmt.Printf("Change %d to %d\n", 57123, zeroToFive(57123))
fmt.Printf("Change %d to %d\n", 2901031, zeroToFive(2901031))
}
|
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;
}
for (int i = 0; i < array.size(); i++) {
if (array.get(i) == 0) {
array.set(i, 5);
}
}
int s = array.size();
for (int j = 0; j < array.size() / 2; j++) {
s--;
int id = array.get(j);
int last = array.get(s);
array.set(j, last);
array.set(s, id);
}
}
public static void main(String[] args) {
int number = 14912400;
replase(number);
System.out.println(array);
}
}
|
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));
rl.close();
});
|
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.replace("0", "5")
user_input = input("Enter the number: ")
print("\n----- Iterative Approach -----")
new_str = replace_0_5_iterative(user_input)
print("Modified number: " + new_str)
print("\n----- Python Replace Approach -----")
new_str = replace_0_5_pythonic(user_input)
print("Modified number: " + new_str)
|
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
main()
{
long long int factorial;
printf("Reverse Factorial > ");
scanf("%lli",&factorial);
reverse_factorial(factorial);
return (0);
} |
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.Printf("%d is %d!\n", target, divisor-1)
return
}
fmt.Printf("%d isn't a factorial number\n", target)
return
}
func main() {
reverseFactorial(720)
reverseFactorial(120)
reverseFactorial(24)
reverseFactorial(362880)
reverseFactorial(12345)
}
|
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) : "NONE");
}
|
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:
print(str(factorial) + " is not a factorial product of any integer.")
factorial = int(input("Reverse Factorial > "))
reversefactorial(factorial)
|
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 int ReverseNumber(int number)
{
var c = number.ToString().ToCharArray();
Array.Reverse(c);
return Int32.Parse(new String(c));
}
}
}
|
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(splits, ""))
return i
}
|
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; //To store the reverse of a number
for(int i=num;i>0;i/=10)
{
int dig=i%10;
reverse=reverse*10+dig;
}
System.out.println("Reverse of the number "+num+" is: "+reverse);
}
}
|
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("Enter the number\n");
scanf("%d", &num);
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
|
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)
{
int r = num%10;
sum = sum*10 + r;
reverse(num/10);
}
return sum;
}
}
|
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(20, 12));
return (0);
}
|
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(18, 1) << endl;
cout << russianPeasant(20, 12) << endl;
return 0;
}
|
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 <<= 2;
b >>= 2;
}
return res;
}
}
class Program
{
static void Main()
{
int number1 = 10;
int number2 = 25;
Console.WriteLine(russ_peasant.multiply(number1, number2));
Console.ReadKey();
}
}
}
|
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
}
return res
}
func main() {
fmt.Println(russianPeasant(18, 24))
fmt.Println(russianPeasant(20, 12))
}
|
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 find Primes. Preferebly pow(10,x)
#define rootSegMax 1000 //root of segMax
bool prime[rootSegMax];
memset(prime, true, sizeof(prime));
for (int i = 2; i * i <= rootSegMax; i++)
if (prime[i])
for (int j = i * i; j < rootSegMax; j += i)
prime[j] = false;
for (int i = 2; i < rootSegMax; i++)
if (prime[i])
Prime.push_back(i);
int low = rootSegMax;
// ^^ lower end of current block we are finding primes for
int high = 2 * rootSegMax;
// ^^ higher end of current block we are finding primes for
int tempMax = Prime.size();
// ^^All non prime numbers will be multiples of these numbers only
while (low < segMax)
{
memset(prime, true, sizeof(prime));
for (int i = 0; i < tempMax; i++)
{
int start = Prime[i] * ceil(1.0 * low / Prime[i]);
for (int j = start; j < high; j += Prime[i])
prime[j - low] = false;
}
for (int i = 0; i < rootSegMax; i++)
if (prime[i])
Prime.push_back( i + low );
low += rootSegMax;
high += rootSegMax;
}
}
int main()
{
segmentedSieve(); //run it to find primes..
//Now Prime contains all the prime numbers upto segMax defined in function
for (size_t i = 0; i < Prime.size(); i++)
cout << Prime[i] << " ";
//^^ Prints all the prime numbers
return 0;
}
|
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("%d ",arr[i]);
printf("\n");
}
int
main()
{
int arr[] = {1 ,2, 3, 4, 5, 6, 7, 8};
int n = sizeof(arr) / sizeof(arr[0]);
shuffle_array(arr, n);
return (0);
}
|
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
arr! a
a
end
end
def test
puts 'Testing Array.shuffle'
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
puts ' Non-manipulated array: '
puts ' ' + array.join(',')
array2 = Shuffler.arr array
puts ' array after Shuffler.arr'
puts ' ' + array.join(',')
puts ' Result of Shuffler.arr'
puts ' ' + array2.join(',')
Shuffler.arr! array
puts ' array after Shuffler.arr!'
puts ' ' + array.join(',')
end
test if $PROGRAM_NAME == __FILE__
|
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 = sqrt(limit);
for (x = 1; x <= wlimit; x++) {
for (y = 1; y <= wlimit; y++) {
z = 4 * x * x + y * y;
if (z <= limit && (z % 60 == 1 || z % 60 == 13 || z % 60 == 17 || z
% 60 == 29 || z % 60 == 37 || z % 60 == 41 || z % 60 == 49
|| z % 60 == 53)) {
sieb[z] = !sieb[z];
}
z = 3 * x * x + y * y;
if (z <= limit && (z % 60 == 7 || z % 60 == 19 || z % 60 == 31 || z
% 60 == 43)) {
sieb[z] = !sieb[z];
}
z = 3 * x * x - y * y;
if (x > y && z <= limit && (z % 60 == 11 || z % 60 == 23 || z % 60
== 47 || z % 60 == 59)) {
sieb[z] = !sieb[z];
}
}
}
for (i = 5; i <= wlimit; i++) {
if (sieb[i] == 1) {
for (j = 1; j * i * i <= limit; j++) {
sieb[j * i * i] = 0;
}
}
}
printf("The following primes have been calculated:\n2\n3\n5");
for (i = 5; i <= limit; i++) {
if (sieb[i] == 1) {
printf("\n%d", i);
}
}
scanf("%d", &i);
return 0;
}
|
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 sieve[limit];
for (int i = 0; i < limit; i++)
sieve[i] = false;
/* Mark siev[n] is true if one of the following is true:
* a) n = (4*x*x)+(y*y) has odd number of solutions, i.e., there exist
* odd number of distinct pairs (x, y) that satisfy the equation and
* n % 12 = 1 or n % 12 = 5.
* b) n = (3*x*x)+(y*y) has odd number of solutions and n % 12 = 7
* c) n = (3*x*x)-(y*y) has odd number of solutions, x > y and n % 12 = 11 */
for (int x = 1; x * x < limit; x++)
for (int y = 1; y * y < limit; y++)
{
// Main part of Sieve of Atkin
int n = (4 * x * x) + (y * y);
if (n <= limit && (n % 12 == 1 || n % 12 == 5))
sieve[n] ^= true;
n = (3 * x * x) + (y * y);
if (n <= limit && n % 12 == 7)
sieve[n] ^= true;
n = (3 * x * x) - (y * y);
if (x > y && n <= limit && n % 12 == 11)
sieve[n] ^= true;
}
// Mark all multiples of squares as non-prime
for (int r = 5; r * r < limit; r++)
if (sieve[r])
for (int i = r * r; i < limit; i += r * r)
sieve[i] = false;
// Print primes using sieve[]
for (int a = 5; a < limit; a++)
if (sieve[a])
cout << a << " ";
}
|
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[] prime = new boolean[limit + 1];
prime[2] = true;
prime[3] = true;
int root = (int) Math.ceil(Math.sqrt(limit));
/** put in candidate primes:
integers which have an odd number of
representations by certain quadratic forms **/
for (int x = 1; x < root; x++)
{
for (int y = 1; y < root; y++)
{
int n = 4 * x * x + y * y;
if (n <= limit && (n % 12 == 1 || n % 12 == 5))
prime[n] = !prime[n];
n = 3 * x * x + y * y;
if (n <= limit && n % 12 == 7)
prime[n] = !prime[n];
n = 3 * x * x - y * y;
if ((x > y) && (n <= limit) && (n % 12 == 11))
prime[n] = !prime[n];
}
}
/** eliminate composites by sieving, omit multiples of its square **/
for (int i = 5; i <= root; i++)
if (prime[i])
for (int j = i * i; j < limit; j += i * i)
prime[j] = false;
return prime;
}
/** Function to get all primes **/
public void getPrimes(int N)
{
boolean[] primes = calcPrimes(N);
display(primes);
}
/** Function to display all primes **/
public void display(boolean[] primes)
{
System.out.print("\nPrimes = ");
for (int i = 2; i < primes.length; i++)
if (primes[i])
System.out.print(i +" ");
System.out.println();
}
/** Main function **/
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Sieve Of Atkin Prime Algorithm Test\n");
/** Make an object of SieveOfAtkin class **/
SieveOfAtkin soa = new SieveOfAtkin();
/** Accept n **/
System.out.println("Enter number to find all primes less than the number\n");
int n = scan.nextInt();
soa.getPrimes(n);
}
}
|
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 integers marked as non-prime
sieve = [0] * n
root = ceil(sqrt(n))
# Flip entry in sieve based on n mod 60=r:
# Per solution to n = 4*x^2 + y^2 if r in [1,13,17,29,37,41,49,53]
# Per solution to n = 3*x^2 + y^2 if r in [7,19,31,43]
# Per solution to n = 3*x^2 - y^2 when y<x if r in [11,23,47,59]
xy = [(x, y) for x in range(1, root + 1) for y in range(1, root + 1)]
for (x, y) in xy:
i = 4 * x * x + y * y
if (i <= n) and (i % 60 in [1, 13, 17, 29, 37, 41, 49, 53]):
sieve[i - 1] ^= 1
i = 3 * x * x + y * y
if (i <= n) and (i % 60 in [7, 19, 31, 43]):
sieve[i - 1] ^= 1
if x > y:
i = 3 * x * x - y * y
if (i <= n) and (i % 60 in [11, 23, 47, 59]):
sieve[i - 1] ^= 1
# Remove multiples of the squares of remaining integers
for i in range(2, root):
j = i * i
while j < n:
sieve[j - 1] = 0
j += i * i
# Add sieved results to the result list
result += [i for (i, n) in list(zip(range(1, n + 1), sieve)) if n == 1]
return result
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.