Sum All Prime Numbers off by just a little

I get 17 for sumPrimes(10) which is correct but for some reason I get 72179 instead of 73156 for sumPrimes(977). For the life of me I can’t find the mistake in my code.

My code so far


function sumPrimes(num) {

  let arr = []

  for(let i = 2; i < num; i++){
      arr.push(i)
  }

  let newArr = arr.filter(value => {
      for(var i = 2; i < value; i++) {
          if(value % i === 0) {
              return false;
          }
      }
      return value > 1;
  })

  return newArr.reduce((acc, val) => acc + val)

}

sumPrimes(10);

Your browser information:

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

Challenge: Sum All Primes

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

Hello gignu.

With this line:

for(let i = 2; i < num; i++){
      arr.push(i)
  }

You are not including the argument itself (977). Think about that, or click to reveal the answer:

for(let i = 2; i < num+1; i++){
      arr.push(i)
  }

I hope this helps

I found the solution. I forgot to add an equal sign in the for loop.

for(let i = 2; i <= num; i++)

1 Like

Thanks for your help! I didn’t even see it yesterday, but thanks anyway :wink: