//typescriptClasses/NumberAlgorithms.ts //Matthew Ellison // Created: 07-13-21 //Modified: 07-13-21 //Algorithms for numbers /* Copyright (C) 2021 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ import { InvalidResult } from "./InvalidResult"; //Generate an infinite sequence of prime numbers using the Sieve of Eratosthenes export function* sieveOfEratosthenes(){ //Return 2 the first time, this lets us skip all even numbers later yield 2; //Dictionary to hold the primes we have already found let dict = new Map(); //Start checking for primes with the number 3 and skip all even numbers for(let possiblePrime = 3;true;possiblePrime += 2){ //If possiblePrime is not in the dictionary it is a new prime number //Return it and mark its next multiple if(!dict.has(possiblePrime)){ yield possiblePrime; dict.set(possiblePrime * possiblePrime, [possiblePrime]); } //If possiblePrime is in the dictionary it is a composite number else{ //Move each witness to its next multiple for(let num of dict.get(possiblePrime)){ let loc: number = possiblePrime + num + num; if(dict.has(loc)){ dict.get(loc).push(num); } else{ dict.set(loc, [num]); } //We no longer need this, free the memory dict.delete(possiblePrime); } } } } export function* sieveOfEratosthenesBig(){ //Return 2 the first time, this lets us skip all even numbers later yield 2n; //Dictionary to hold the priems we have already found let dict = new Map(); //Start checking for primes with the number 3 and skip all even numbers for(let possiblePrime = 3n;true;possiblePrime += 2n){ //If possiblePrime is not in the dictionary it is a new prime number //Return it and mark its next multiple if(!dict.has(possiblePrime)){ yield possiblePrime; dict.set(possiblePrime * possiblePrime, [possiblePrime]); } //If possiblePrime is in the dictionary it is a composite number else{ //Move each witness to its next multiple for(let num of dict.get(possiblePrime)){ let loc: bigint = possiblePrime + num + num; if(dict.has(loc)){ dict.get(loc).push(num); } else{ dict.set(loc, [num]); } //We no longer need this, free the memory dict.delete(possiblePrime); } } } } //This returns the sqrt of the bigint passed in export function sqrtBig(value: bigint): bigint{ if(value < 0n){ throw "Negative numbers are not supported"; } let k = 2n; let o = 0n; let x = value; let limit = 100; while(x ** k !== k && x !== o && --limit){ o = x; x = ((k - 1n) * x + value / x ** (k - 1n)) / k; } return x; } //Returns an array with all Fibonacci numbers up to goalNumber export function getAllFib(goalNumber: number): number[]{ //Setup the variables let fibNums: number[] = []; //If the number is <= 0 return an empty list if(goalNumber <= 0){ return fibNums; } else if(goalNumber == 1){ fibNums.push(1); return fibNums; } //This means that at least 2 1's are elements fibNums.push(1); fibNums.push(1); //Loop to generate the rest of the Fibonacci numbers while(fibNums[fibNums.length - 1] <= goalNumber){ fibNums.push((fibNums[fibNums.length - 1]) + (fibNums[fibNums.length - 2])); } //At this point the most recent number is > goalNumber, so remove it and return the rest of the list fibNums.pop(); return fibNums; } export function getAllFibBig(goalNumber: bigint): bigint[]{ //Setup the variables let fibNums:bigint[] = []; //If the number is <= 0 return an empty list if(goalNumber <= 0){ return fibNums; } else if(goalNumber == 1n){ fibNums.push(1n); return fibNums; } //This means that at least 2 1's are elements fibNums.push(1n); fibNums.push(1n); //Loop to generate the rest of the Fibonacci numbers while(fibNums[fibNums.length - 1] <= goalNumber){ fibNums.push((fibNums[fibNums.length - 1]) + (fibNums[fibNums.length - 2])); } //At this point the most recent number is > goalNumber, so remove it and return the rest of the list fibNums.pop(); return fibNums; } //Returns an array with all primes up to goalNumber export function getPrimes(goalNumber: number): number[]{ let primes: number[] = []; //Holds the prime numbers let foundFactor: boolean = false; //A flag for whether a factor of the current number has been found //If the number is 0 or a negative return an empty list if(goalNumber <= 1){ return primes; } //Optherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2); } //We can now start at 3 and skip all even numbers, because they cannot be prime for(let possiblePrime: number = 3;possiblePrime <= goalNumber;possiblePrime += 2){ //Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: number = Math.ceil(Math.sqrt(possiblePrime)); //We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this for(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of range if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort((n1, n2) => n1 - n2); return primes; } export function getPrimesBig(goalNumber: bigint): bigint[]{ let primes: bigint[] = []; //Holds the prime numbers let foundFactor: boolean = false; //A flag for whether a factor of the current number has been found //If the number is 0 or a negative return an empty list if(goalNumber <= 1){ return primes; } //Optherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2n); } //We can now start at 3 and skip all even numbers, because they cannot be prime for(let possiblePrime: bigint = 3n;possiblePrime <= goalNumber;possiblePrime += 2n){ //Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: bigint = sqrtBig(possiblePrime); //We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this for(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0n){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of range if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort(function(n1, n2){ if(n1 > n2){ return 1; } else if(n1 < n2){ return -1; } else{ return 0; } }); return primes; } //Returns an array with numberOfPrimes prime elements export function getNumPrimes(numberOfPrimes: number): number[]{ let primes: number[] = []; //Holds the prime numbers let foundFactor: boolean = false; //A flag for whether a factor of the current number has been found //If the number is 0 or negative return an empty list if(numberOfPrimes <= 1){ return primes; } //Otherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2); } //We can now start at 3 and skip all even number, because they cannot be prime for(let possiblePrime: number = 3;primes.length < numberOfPrimes;possiblePrime += 2){ //Check all the current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: number = Math.ceil(Math.sqrt(possiblePrime)); //We can safely assume that there will be at least 1 element in the primes list because of 2 being added by default for(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of bounds if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort((n1, n2) => n1 - n2); return primes; } export function getNumPrimesBig(numberOfPrimes: bigint): bigint[]{ let primes: bigint[] = []; //Holds the prime numbers let foundFactor: boolean = false; //A flag for whether a factor of the current number has been found //If the number is 0 or negative return an empty list if(numberOfPrimes <= 1){ return primes; } //Otherwise the number is at least 2, so 2 should be added to the list else{ primes.push(2n); } //We can now start at 3 and skip all even number, because theyu cannot be prime for(let possiblePrime: bigint = 3n;primes.length < numberOfPrimes;possiblePrime += 2n){ //Check all the current primes, up to sqrt(possiblePrime), to see if there is a divisor let topPossibleFactor: bigint = sqrtBig(possiblePrime); //We can safely assume that ther ewill be at least 1 element in the primes list because of 2 being added by default for(let primesCnt: number = 0;primes[primesCnt] <= topPossibleFactor;){ if((possiblePrime % primes[primesCnt]) == 0n){ foundFactor = true; break; } else{ ++primesCnt; } //Check if the index has gone out of bounds if(primesCnt >= primes.length){ break; } } //If you didn't find a factor then the current number must be prime if(!foundFactor){ primes.push(possiblePrime); } else{ foundFactor = false; } } //Sort the list before returning it primes = primes.sort(function(n1, n2){ if(n1 > n2){ return 1; } else if(n1 < n2){ return -1; } else{ return 0; } }); return primes; } //Returns true if possiblePrime is prime export function isPrime(possiblePrime: number): boolean{ if(possiblePrime <= 3){ return possiblePrime > 1; } else if(((possiblePrime % 2) == 0) || ((possiblePrime % 3) == 0)){ return false; } for(let cnt: number = 5;(cnt * cnt) <= possiblePrime;cnt += 6){ if(((possiblePrime % cnt) == 0) || ((possiblePrime % (cnt + 2)) == 0)){ return false; } } return true; } export function isPrimeBig(possiblePrime: bigint): boolean{ if(possiblePrime <= 3n){ return possiblePrime > 1n; } else if(((possiblePrime % 2n) == 0n) || ((possiblePrime % 3n) == 0n)){ return false; } for(let cnt : bigint = 5n;(cnt * cnt) <= possiblePrime;cnt += 6n){ if(((possiblePrime % cnt) == 0n) || ((possiblePrime % (cnt + 2n)) == 0n)){ return false; } } return true; } //Returns an array with all the factors of goalNumber export function getFactors(goalNumber: number): number[]{ //You need to get all the primes that could be factors of this number so you can test them let topPossiblePrime: number = Math.ceil(Math.sqrt(goalNumber)); let primes: number[] = getPrimes(topPossiblePrime); let factors: number[] = []; //You need to step through each prime and see if it is a factor in the number for(let cnt: number = 0;cnt < primes.length;){ //If the prime is a factor you need to add it to the factor list if((goalNumber % primes[cnt]) == 0){ factors.push(primes[cnt]); goalNumber /= primes[cnt]; } //Otherwise advance the location in primes you are looking at //By not advancing f the prime is a factor you allow for multiple of the same prime number as a factor else{ ++cnt; } } //If you didn't get any factors the number itself must be a prime if(factors.length == 0){ factors.push(goalNumber); goalNumber /= goalNumber; } //If for some reason the goalNumber is not 1 throw an exception if(goalNumber != 1){ throw new InvalidResult("The factor was not 1: " + goalNumber); } //Return the list of factors return factors; } export function getFactorsBig(goalNumber: bigint): bigint[]{ //You need to get all the primes that could be factors of this number so you can test them let topPossiblePrime: bigint = sqrtBig(goalNumber); let primes: bigint[] = getPrimesBig(topPossiblePrime); let factors: bigint[] = []; //You need to step through each prime and see if it is a factor in the number for(let cnt: number = 0;cnt < primes.length;){ //If the prime is a factor you need to add it to the factor list if((goalNumber % primes[cnt]) == 0n){ factors.push(primes[cnt]); goalNumber /= primes[cnt]; } //Otherwise advance the location in primes you are looking at //By not advancing f the prime is a factor you allow for multiple of the same prime number as a factor else{ ++cnt; } } //If you didn't get any factors the number itself must be a prime if(factors.length == 0){ factors.push(goalNumber); goalNumber /= goalNumber; } //If for some reason the goalNumber is not 1 throw an exception if(goalNumber != 1n){ throw new InvalidResult("The factor was not 1: " + goalNumber); } //Return the list of factors return factors; } //Returns an array with the prime divisors of goalNumber export function getDivisors(goalNumber: number): number[]{ let divisors: number[] = []; //Start by checking that the number is positive if(goalNumber <= 0){ return divisors; } //If the number is 1 return just itself else if(goalNumber == 1){ divisors.push(1); return divisors; } //Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly let topPossibleDivisor: number = Math.ceil(Math.sqrt(goalNumber)); for(let possibleDivisor = 1;possibleDivisor <= topPossibleDivisor;++possibleDivisor){ //If you find one add it and the number it creates to the list if((goalNumber % possibleDivisor) == 0){ divisors.push(possibleDivisor); //Account for the possibility of sqrt(goalNumber) being a divisor if(possibleDivisor != topPossibleDivisor){ divisors.push(goalNumber / possibleDivisor); } if(divisors[divisors.length - 1] == (possibleDivisor + 1)){ ++possibleDivisor; } } } //Sort the list before returning it for neatness divisors.sort((a, b) => a - b); //Return the list return divisors; } export function getDivisorsBig(goalNumber: bigint): bigint[]{ let divisors: bigint[] = []; //Start by checking that the number is positive if(goalNumber <= 0n){ return divisors; } //If the number is 1 return just itself else if(goalNumber == 1n){ divisors.push(1n); return divisors; } //Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly let topPossibleDivisor: bigint = sqrtBig(goalNumber); for(let possibleDivisor = 1n;possibleDivisor <= topPossibleDivisor;++possibleDivisor){ //If you find one add it and the number it creates to the list if((goalNumber % possibleDivisor) == 0n){ divisors.push(possibleDivisor); //Account for the possibility of sqrt(goalNumber) being a divisors if(possibleDivisor != topPossibleDivisor){ divisors.push(goalNumber / possibleDivisor); } if(divisors[divisors.length - 1] == (possibleDivisor + 1n)){ ++possibleDivisor; } } } //Sort the list before returning it for neatness divisors.sort((a, b) => { if(a > b){ return 1; } else if(a < b){ return -1; } else{ return 0; } }); //Return the list return divisors; } //Returns F[goalSubscript] export function getFib(goalSubscript: number): number{ //Setup the variables let fibNums: number[] = [1, 1, 0]; //A list to keep track of the Fibonacci numbers. It need only be 3 long because we only need the one we are working on and the last 2 //If the number is <= 0 return 0 if(goalSubscript <= 0){ return 0; } //Loop through the list, generating Fibonacci numbers until it finds the correct subscript let fibLoc: number = 2; for(fibLoc = 2;fibLoc < goalSubscript;++fibLoc){ fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3] + fibNums[(fibLoc - 2) % 3]; } //Return the proper number. The location counter is 1 off of the subscript return fibNums[(fibLoc - 1) % 3]; } export function getFibBig(goalSubscript: bigint): bigint{ //Setup the varibles let fibNums: bigint[] = [1n, 1n, 0n]; //A list to keep track of the Fibonacci numbers. It need only be 3 long because we only need the one we are working on and the last 2 //If the number is <= 0 return 0 if(goalSubscript <= 0n){ return 0n; } //Loop through the list, generating Fibonacci numbers until it finds the correct subscript let fibLoc: bigint = 2n; for(fibLoc = 2n;fibLoc < goalSubscript;++fibLoc){ fibNums[Number(fibLoc % 3n)] = fibNums[Number((fibLoc - 1n) % 3n)] + fibNums[Number((fibLoc - 2n) % 3n)]; } //Return the proper number. The location counter is 1 off of the subscript return fibNums[Number((fibLoc - 1n) % 3n)]; } //This function returns the GCD of the two numbers sent to it export function gcd(num1: number, num2: number){ while((num1 != 0) && (num2 != 0)){ if(num1 > num2){ num1 %= num2; } else{ num2 %= num1; } } return num1 | num2; } export function gcdBig(num1: bigint, num2: bigint){ while((num1 != 0n) && (num2 != 0n)){ if(num1 > num2){ num1 %= num2; } else{ num2 %= num1; } } return num1 | num2; } //Return the factorial of the number passed in export function factorial(num: number): number{ let fact: number = 1; for(let cnt = 1;cnt <= num;++cnt){ fact *= cnt; } return fact; } export function factorialBig(num: bigint): bigint{ let fact: bigint = 1n; for(let cnt = 1n;cnt <= num;++cnt){ fact *= cnt; } return fact; } //Converts a number to its binary equivalent export function toBin(num: number): string{ return (num >>> 0).toString(2); } export function toBinBig(num: bigint): string{ let binNum = ""; while(num > 0n){ let rest = num % 2n; if(rest == 1n){ binNum += "1"; } else{ binNum += "0"; } num = (num - rest) / 2n; } binNum = binNum.split("").reverse().join(""); if(binNum == ""){ binNum = "0"; } return binNum; }