I have the following method:
public static boolean[] mk2(int n) {
boolean[] isPrime = new boolean[n + 2];
isPrime[1] = false;
isPrime[2] = true;
for (int i = 3; i <= n; i++) {
if((i & 1) == 0) {
isPrime[i] = false;
} else {
isPrime[i] = true;
}
}
// cycle through to see if a number has factors other than 1 & itself
for(int y = 3; y <= n; y++) {
System.out.print("Test y " + y);
if(isPrime[y]) {
for(int i = 2; i <= y-1; i++) {
if(y%i==0){
// stop here if it isn't prime
isPrime[y] = false;
System.out.println(" disproved");
i = y + 1;
}
}
if(isPrime[y]){
System.out.println(" is prime and disproves:");
for (int j = y; y*j <= n; j++) {
if(y*j<=n) {
isPrime[y*j] = false;
System.out.print(" "+(y*j)+" ");
}
}
System.out.println(".");
}
} else {
System.out.println(" already disproved");
}
}
System.out.println("Primes");
int x = 0;
for(int i=1; i <= n; i++) {
if(isPrime[i]) {
System.out.print(i+", ");
x++;
}
if(x >= 61) {
System.out.println(";");
x = 0;
}
}
System.out.println(".");
return isPrime;
}
which generally works fine but when I set n to 100000 I get the following exception java.lang.ArrayIndexOutOfBoundsException: -2146737495
from what I have been able to find java.lang.ArrayIndexOutOfBoundsException
normally occurs when you try to access a point in the array greater than its defined size e.g.
int[] x = new int[5];
x[10] = 2;
so I am a bit confused as to what is happening here. Any Ideas?