I am trying to run this code to print the sum of all the prime numbers less than 2 million. This loop is never ending. Can anyone tell me what is wrong with the code? It seems to work with smaller numbers though.
public static void main(String[] args) {
long result = 1;
for(int i=0; i<2000000; i++) {
if(isPrime(i)) {
result+= i;
}
}
System.out.println(result);
}
private static boolean isPrime(long n) {
boolean result = false;
for(long i=2; i<(long)Math.sqrt(n); i++) {
if(n%i == 0) {
result = false;
break;
}
else result = true;
}
return result;
}
In
isPrimeyou are only testing division by 2:it should be division by every
iand starting from 2:Practically in your current version an odd number
nwill keep dividing by 2 up ton/2instead of stopping much sooner. Consider n = 21. You are dividing by 2 from 1 to 10, instead of dividing by 3 at the 3rd step and exiting.It not only gives incorrect results, but also takes much longer than needed to reach a
returnstatement.Edit: For faster results check out this sieve of Erathostenes method:
Edit #2: Found some bugs with your new version. Here’s the corrected one: