Prime numbers challenge

Prime numbers challenge
0.0 0

#1

I am working on this sum all the primes. My implementation is below. It warns me that there might be infinite loops and if I choose not to be protected against infinite loops my browser might crash. And my browser does crash. I don’t know if this is related to memory or runtime constraints. A similar implementation of the same code (in another language) works. I did everything to speed it up but no luck. Does anybody have an idea?

//
function sumPrimes(num) {
  var result = 2;
  var primes = [2];
  if (num < 2) return 0;
  for(i = 3; i <= num; i++){
    if (isPrime(i, primes)) {
      primes.push(i);
      result += i;
    }
  }
  return result;
}


function isPrime(num, primes) {
  for(i = 0; i < primes.length; i++) {
    if (num % primes[i] === 0) { //divisible by a prime number
      return false;
    }
    if(primes[i]*primes[i] > num){ //no need to check numbers higher than num^0.5
      return true;
    }
  }
  return true;
}

sumPrimes(97);


#2
for (i = 3; i <= num; i++){
...
for(i = 0; i < primes.length; i++) {

When you use a variable without first declaring it with the var keyword it creates a global variable. This means that both of your for loops are modifying the same iterator.


#3

That makes perfect sense! I am still trying to grasp how the scope of variables work. Thank you very much!


#4