I am trying to find the sum of all prime numbers <=2 million so i used sieve of Eratosthenes TO mark all prime numbers .As i declared the boolean array of size 2 million ,i got this error
"main" java.lang.ArrayIndexOutOfBoundsException: 2000000
Since the sum can be two large so i used long instead of sum .here is the code in java
public class Summationofprimes {
static long[] isprime=new long[2000000];
static void sieve(){
Arrays.fill(isprime, 0);//all marked false
isprime[1]=1;isprime[0]=1;
for(int i=2;i*i<=2000000;i++){
if(isprime[i]==0){
// print(i);
// sum+=i;
//print(sum);
for(int j = i * i; j <= 2000000 ;j += i){
isprime[j]=1;// all multiples marked true
}
}
}
}
public static void main(String[] args) {
sieve();
long sum=0;
System.out.println("sum is :");
for(int i=2;i<=2000000;i++){
if(isprime[i]==0){
sum+=i;
}
}
System.out.println(sum);
// TODO Auto-generated method stub
}
}
How do i fix this issue in code ?