I thought I’d reply to this thread because I think my solution is similar to the OP’s but I am always missing the last integer to include in the final function.
function sumPrimes(num) {
const sieve = new Array(num).fill(true)
for (let x = 2; x <= Math.sqrt(num); x++) {
if (sieve[x]) {
for (let y = Math.pow(x, 2); y <= num; y += x) {
sieve[y] = false
}
}
}
return sieve.reduce((primesArray, prime, index) => {
if (prime && index > 1) {
primesArray.push(index);
}
return primesArray;
}, []).reduce((x, y) => x + y);
}
I followed the Sieve of Eratosthenes algorithm found in Wikipedia and it always fails to take the last element of the array into calculation. So sumPrimes(10) will correctly output 17 but sumPrimes(23) will output 77 instead of 100. Can anyone help me with my code, please?
I should probably clarify why I think you needed to do this, it’s from this line in the wikipedia article:
Let A be an array of Boolean values, indexed by integers 2 to n
and your line: const sieve = new Array(num).fill(true)
Array of booleans - check
Indexed by integers 2 to n - not check
Your array is indexed by 0 to n-1, and hence causes the problem - sieve[n] starts undefined (which is falsey), and if it ever gets accessed it would only be to set it to false
you correctly set sieve[0] and sieve[1] to false implicitly by ignoring them in the sum (though you could just set them to false in the sieve function)