Possible Duplicate:
How much time should it take to find the sum of all prime numbers less than 2 million?
I am trying to implement a simple sieve of erathosthenes to solve this question on project euler :
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
My code keeps returning the wrong answer though - I keep getting 142889228620 which project euler isn't accepting.
Can anyone give me any hints as to why? Here is the code:
import java.math.BigInteger;
public class Prime {
/*
* Input: an integer n > 1
*
* Let A be an array of bool values, indexed by integers 2 to n, initially
* all set to true.
*
* for i = 2, 3, 4, ..., while i^2 ≤ n: if A[i] is true: for j = i^2, i^2 +
* i, i^2 + 2i, ..., while j ≤ n: A[j] = false
*
* Now all i such that A[i] is true are prime.
*/
import java.math.BigInteger;
public class Prime {
/*
* Input: an integer n > 1
*
* Let A be an array of bool values, indexed by integers 2 to n, initially
* all set to true.
*
* for i = 2, 3, 4, ..., while i^2 ≤ n: if A[i] is true: for j = i^2, i^2 +
* i, i^2 + 2i, ..., while j ≤ n: A[j] = false
*
* Now all i such that A[i] is true are prime.
*/
public static void main(String[] args) {
boolean[] array = new boolean[2000000];
BigInteger counter = new BigInteger("0");
for (int value = 0; value < array.length; value++) {
array[value] = true;
}
for (int i = 2; i < array.length; i++) {
if (array[i]) {
int j = i * i;
while (j > 0 && j < array.length) {
array[j] = false;
j += i;
}
}
}
for (int i = 2; i < array.length; i++) {
if (array[i]) {
counter = counter.add(BigInteger.valueOf(i));
}
}
for (int value = 2; value < array.length; value++) {
if(array[value]){
System.out.println(value + ", ");
}
}
System.out.println("\n" + counter);
}
}