Sum of All Prime Numbers - I don't get it

Tell us what’s happening:
So I passed this challenge, but I’m having trouble understanding an aspect of it. I took the advice in the hints section and borrowed code for the prime number generator. I spend a decent amount of time looking at possibilities because I wanted to understand the generator. I thought I understood this one, but now I’m not sure.

With counter and i both set to 2 at the beginning I don’t see how the if statement ever evaluates to true and weeds out the non-primes.

Your code so far


function sumPrimes(num) {
let primeArray = [];

for (var counter = 2; counter <= num; counter++) {

var notPrime = false;
for (var i = 2; i <= counter; i++) {
    if (counter%i===0 && i!==counter) {
        notPrime = true;
        
    }
}
if (notPrime === false) {
            primeArray.push(counter);
}
}

return primeArray.reduce((x, y) => x + y);

}

sumPrimes(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36.

Challenge: Sum All Primes

Link to the challenge:

I assume you’re referring to this code?

for (var i = 2; i <= counter; i++) {
    if (counter%i===0 && i!==counter) {
        notPrime = true;
    }
}

Perhaps your confusion is with counter%i===0. Note that it is not checking if counter or i are equal to 0 - they are checking if i divides evenly into counter using the modulus operator (%). For example, if counter were 12 and i were 3, then counter%i would be 0, so (counter%i===0 && i!==counter) would evaluate to true.

1 Like

Oh I figured it out. I was falsely assuming that since they are both declared with an initial value of 2 ( var i and var counter) that they would both continue to increment at the same rate, but I wasn’t accounting for the fact that each time the top for loop goes through its loop that the nested one resets back to i = 2.

Thanks! :slight_smile:

1 Like