I am having trouble finding primes. I implemented Sieve but not sure if its correct. Any help is appreciated
/*algorithm Sieve of Eratosthenes is
input: an integer n > 1.
output: all prime numbers from 2 through n.
let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n do
if A[i] is true
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
A[j] := false
return all i such that A[i] is true.
*/
function sumPrimes(num) {
let booleanResult = [];
let numResult = [];
let limitsqrRoot = Math.sqrt(num);
//initializing array
for (let i = 0;i < num;i++){
booleanResult.push(true);
}
for (let i = 1;i <= limitsqrRoot;i++){
if (booleanResult[i]){
for (let j = i*2;j <= num;j += i){
booleanResult[j] = false;
}
}
}
for(let i = 2;i <= booleanResult.length;i++){
if(booleanResult[i]){
numResult.push(i);
}
}
return numResult.reduce((total,current) => total+current);
}
console.log(sumPrimes(977));// I am getting 72179
// should be 73156
The only even prime number is 2. So you never need to check if any other prime number is even.
The details are a bit delicate, but you can make your array ‘booleanResult’ only track even numbers.
You can also get a little performance boost to use this array to sum instead of making and reducing the ‘numResult’ array.
The last thing you can do is somewhat ‘non JavaScripty’, but you can actually preallocate an array, which is much faster than making an array with push.
I will note, except for the even bit (with should cut your time in half), these changes will be pretty small unless num is big.