Sum All Primes - Is it possible to solve this with the approach I have in mind?

This is my approach:

For loop to check every number equal to or less than num is a prime.

This number is passed into the function isPrime, which will determine if the number is prime. If it is prime, it’s value will be added to the total global variable. If it is not prime, then nothing happens.

I have tried the test case sumPrimes(10) and I get 18 as the returned value instead of 17. So, I am off by one…

Can someone please inspect and advise on how to improve my code?

Your code so far


function sumPrimes(num) {

let total = 0;

for (let i = 0 ; i <= num ; i++) {

  isPrime(i)
  function isPrime (i) {
    
    for (let j = 2 ; j < i ; j++) {
      if (i % j == 0) {
        return false
      }
    }
    return true
  }

    if ((isPrime(i) == true)) {
    total = total + i
    }
    
}



  
return total

}

sumPrimes(10);

Your browser information:

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

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

Try printing out what is being added to ‘total’ (as in – console.log(i) right before you add i to the total. You might see a number that isn’t supposed to be there – and be sure to re-read the conditions under which a number is prime as stated in the problem.

1 Like

Thanks I see now.

1 was being added each time when it shouldn’t have.

The correction and solution below:

function sumPrimes(num) {

let total = 0;

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

  isPrime(i)
  function isPrime (i) {
    
    for (let j = 2 ; j < i ; j++) {
      if (i % j == 0) {
        return false
      }
    }
    return true
  }

    if ((isPrime(i) == true)) {
    total = total + i
    }
    
}



  
return total

}

@NiSofwareEngineer It is not necessary to show your final solution. In fact, we would prefer users not post full working solutions in forum posts to avoid spoiling it for another user.

Thanks.