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/