I’m trying to solve a mathematical problem from http://projecteuler.net using javascript: to find the sum of all the primes below two million. When I run the script I wrote, my browser crashes (I’m using Google Chrome). This is the script:
function isPrime(num)
{
if(num < 2)
return false;
for (var i = 2; i < num; i++)
{
if(num%i==0)
return false;
}
return true;
}
var total=0e1;
for (var i = 1; i < 2000000; i++)
{
if(isPrime(i))
{
total=total+i;
}
}
document.write("The sum of all the primes below two million is ",total);
The script works fine for smaller numbers (i<100000). What is wrong with it? How can I fix it? Thanks for your help.
The function
isPrimeperforms n modulo operations for each n you check (because you check every single number less than the prime as a factor). Assuming about one in every seven numbers is prime, that means you are performing theisPrimefunction about 28,000 times in your snippet, and you are performing the modulo operation about 392 million times. Likely, Chrome is crashing because it assumes the JavaScript engine has entered an infinite loop.As NullUserException said, there are better ways of finding primes.
A naive improvement would be to only check for factors of a number that are less than its square root. For any number a where a = b * c, you can assume that either b or c is less than the square root of a. Since you only need to know one factor to know that a number is not prime, you only need to look for factors less than its square root. As lanzz commented, you can also skip even numbers.
Don’t mistake me; this won’t change the O complexity of your algorithm, and you are still going to crash the JavaScript engine with a big enough number. But it will raise the number at which it crashes. I’m not sure if it will work up to 2 million.