I’m not sure what is wrong with my code. Am I on the right track?
Sorry I’m still a novice with JS.
function sumPrimes(num) {
var sum = 0;
var currentVal = 2;
while (currentVal <= num) {
for (var i = 2; i < currentVal; i++) {
if (currentVal % i == 0) {
continue;
} else {
sum += currentVal;
}
}
currentVal++;
}
return sum;
}
console.log(sumPrimes(10));
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36.
Its supposed to mean:
“If the current value divided by the value of i has no remainder then it is not a prime number, so then move onto the next value (currentVal += 1).
Otherwise, if it has a remainder, then add to the sum total.”
Is the problem that I am adding to the sum values that aren’t actually prime numbers?
Right, so what my code currently says is this:
“If i divides evenly into currentVal then skip to i += 1.
Otherwise, if i does NOT divide evenly into currentVal, add currentVal to sum.”
But what I realize now is I’m not checking all possible values of i < currentVal before adding currentVal to sum. I’m adding currentVal as soon as one particular value of i does not divide evenly without checking the rest of possible values.
Is this my error?
Exactly. You are currently adding currentVal to the sum for each number less than currentVal that does not divide into currentVal. So you have the right piece being combined in a way that isn’t quite what you want.
Hey Jeremy. So I stuck with it, tinkered with my code and I got it to work!
I incorporated a boolean flag.
function sumPrimes(num) {
var sum = 0;
var currentVal = 2;
var flag = true;
while (currentVal <= num) {
for (var i = 2; i < currentVal; i++) {
if (currentVal % i == 0) {
flag = false;
break;
} else {
flag = true;
}
}
if (flag) {
sum += currentVal;
}
currentVal++;
}
return sum;
}
console.log(sumPrimes(10));