Reputation: 11
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
public class Problem10
{
public static void main(String[] args)
{
int sum = 17;
for(long i=11; i<2000000; i+=2)
{
if(isPrime(i)) sum += i;
}
System.out.println(sum);
}
public static boolean isPrime(long n)
{
if(n==2) return true;
if(n%2 == 0) return false;
for(long i=3; i<= Math.sqrt(n); i+=2)
{
if(n%i == 0) return false;
}
return true;
}
}
I don't see what is wrong with this. It keeps printing 1179908154 which is incorrect.
Upvotes: 0
Views: 104
Reputation: 178263
Your sum
is an int
, but integer overflow is occurring. If you change the datatype to long
, then the answer changes to 142913828922
, which is longer than the maximum possible int
. That appears to be the correct answer.
Upvotes: 3