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