Added Sieve of Eratosthenes

This commit is contained in:
2021-07-01 10:57:28 -04:00
parent bb5b8154ae
commit a6a83f6c73
2 changed files with 98 additions and 1 deletions

View File

@@ -65,6 +65,73 @@ export function sqrtBig(value: bigint): bigint{
return x;
}
//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<number, number[]>();
//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<bigint, bigint[]>();
//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);
}
}
}
}
export function getAllFib(goalNumber: number): number[]{
//Setup the variables
let fibNums: number[] = [];