SumPrimes Nested Loops Solution - Is my logic flawed?

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.

Challenge: Sum All Primes

Link to the challenge:

Can you describe, in words, what this if-else is supposed to do?

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?

Two problems with that description:

  1. having no remainder means that i divides evenly into currentVal

  2. a number greater than 2 is prime if no values other than 1 and itself divide evenly into it

  1. 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.

1 Like

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));
1 Like

Nice work figuring it out. As a bonus question, how can you change this one line to make it faster?

1 Like

I only know this from peeking at the provided solutions:

for (var i = 2; i <= Math.sqrt(currentVal); i++) {

The logic is that the square root of a number is the largest unique divisor possible.

1 Like

I like those solutions - I think they present three interesting ways to look at the problem.

1 Like