Hi everyone. Can someone explain why “sieve.push(j)” below doesn’t work to add the multiples of i to sieve (the list of composite numbers?) I’ve seen from a few solutions that sieve[j]=true works instead, but I never would have thought of that, so I’d like to understand why my more beginner approach doesn’t do the trick. Thanks in advance for any suggestions!
function sumPrimes(num) {
//sieve for composites, primes for primes
var i, j, k, total=0, sieve=[], primes=[];
//if i hasn't been added to sieve, add to primes and add all of its multiples to sieve up to num/max
function getPrimes(max) {
for (i=2; i<=max; i++) {
if (sieve.indexOf(sieve[i]) < 0) {
primes.push(i);
for (j = i*2; j<=max; j+=i) {
sieve.push(j);
}
}
}
return primes;
}
//Add up primes. Need to call getPrimes using num
primes = getPrimes(num);
for (k = 0; k<primes.length; k++ ) {
total+= primes[k];
}
return total;