Sum All Primes What's wrong?

Sum All Primes What's wrong?
0.0 0

#1

Tell us what’s happening:
So the logic I followed is the common prime logic(I guess it’s correct, maybe):
if the number (i) is 2 or 3, then it’s prime and push into the array. If n > 3, then I divide it by every integer between 2 and square root of n and, if I get a positive remainder every time, then it’s prime. then at the end, I sum them all the array to get the result which is the sum of the primes.

I feel that the mistake is in the second loop(the loop which I use to see if i is prime or not) but I don’t know. Any help please?

Your code so far


function sumPrimes(num) {
  var arr = [];
  for (var i = 2; i < num; i++) {
    if(i === 2 || i === 3) {
      arr.push(i);
    }
    if (i > 3) {
    for (var j = 2; j < Math.sqrt(i);j++) {
    if (i % j > 0) {
      arr.push(i);
    }
    else {
      break;
    }
    } 
    }
  }
    console.log(arr);
    return arr.reduce((before,after) => before + after);
}

sumPrimes(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

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


#2

Your arr returns 2, 3, 5, 7, 9.
9 is not a prime number :slight_smile:


#3

I know that and that’s why I posted this at first place :roll_eyes:


#4
for (var j = 2; j < Math.sqrt(i);j++) {
    if (i % j > 0) {
      arr.push(i);
    }

When i = 9,
you have j = 2,
Math.sqrt(9) becomes 3,
2 < 3 becomes true,
9 % 2 becomes 1 => true,
therefore 9 gets pushed into your array.

There is your problem.


#5

You are pushing any odd number, as for those i % j on the first iteration is 1.

You should sum those numbers for which none of the numbers up to and including Math.sqrt(i) evenly divide i. So push only after the for loop (after you’ve tested all potential divisors), and only if the number passed the for loop with all i % j > 0.

Use j <= Math.sqrt(i)

And give your reduce a starting value of 0. Otherwise, sumPrimes(1) would result in an error.


#6

I know that. The problem is that I don’t know how I do it. I tried break, I tried continue, I tried to put a condition after the loop ends, I tried to push the value after the loop ends, nothing works.


#7

Thank you! I now understand, it works!