mirror of
https://bitbucket.org/Mattrixwv/typescriptclasses.git
synced 2025-12-06 18:33:59 -05:00
Added Sieve of Eratosthenes
This commit is contained in:
@@ -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[] = [];
|
||||
|
||||
Reference in New Issue
Block a user