Sum All Primes Logic(Or there lack off)

Sum All Primes Logic(Or there lack off)
0

#1

Tell us what’s happening:

Please ignore the console.log lines, I commented them out. I just use them for testing. What exactly am I doing wrong here? Is it off -by-one error, comparison operator , or something else? This happens when I try to use the global array reduce function too( in another exercise). I seem to not quite grasp looping as I think I do. For small edge cases (like numbers below 100), my code returns the desired value(s), but as the numbers get larger, somehow my code does not work.

Your code so far


function sumPrimes(num) {

for(let i = 2; i<=num ; i++){
    if(i === 2 || i === 3 || i === 5 || i === 7 || (i % 2 !==0  && i % 3 !== 0 && i % 5 !== 0 && i % 7 !== 0 ) ){
      sumPrimes += i;
      // console.log(`${i}, sumPrimes is: ${sumPrimes} and num is: ${num}`);

}
}
//console.log(`${sumPrimes}, num is : ${num}`); 
return sumPrimes;
}


Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/


#2

Well, I think your way of detecting if something is prime is not robust/not taking into account all primes. For example what about 169? Is that a prime number? 13 x 13 = 169.


#3

Roger that, let me mull over the problem some more …


#4

Wikipedia article on the sieve of eratosthenes actually helps alot.


#5

Thank you. That was so informative. @snowmonkey.