Tell us what’s happening:
Can someone tell me what is wrong with my code?
So, what I’ve tried is this -
Next value will keep increasing by 1 until the given num. Now, only if the next value is a prime number i.e divisible by itself or by 1, the curr value will change to the next value. So, in this way, the curr value will always be a prime number. Thus, I can just add the curr value and sum and save it in sum.
I’m getting 27 when I pass 7 as the num, which is incorrect.
Your code so far
function sumPrimes(num) {
var prev = 0;
var curr = 1;
var next = 2;
var sum = 0;
while (next <= num) {
if (next % next == 0 && next % 1 == 0) {
prev = curr;
curr = next;
sum += curr;
}
next++;
}
return sum;
}
sumPrimes(7);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes