Intermediate Algorithm Scripting - Sum All Primes

Tell us what’s happening:
My issue is that my results are off by 1 and I don’t understand why?

  **Your code so far**
function sumPrimes(num) {
let arr = [1];
for (let i = 2; i <= num; i++){
  let div = 0;
   for (let j = 0; j < arr.length; j++){
     if (i % arr[j] == 0){
       div++;
     }
   }
   if (div == 1){
      arr.push(i)
    }
}
console.log(arr)
num = arr.reduce((a,b) => a+b);
console.log(num)
return num;
}

sumPrimes(10);
sumPrimes(977)
  **Your browser information:**

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

Challenge: Intermediate Algorithm Scripting - Sum All Primes

Link to the challenge:

1 is not a prime number.

Note that you can stop checking if you have a prime once you find a prime divisor.

1 Like

That makes sense, thank you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.