Array size is maximum 2^31-1, in theory, which is an integer. Your n+1
is a long. So that doesn't match. You will need to cast the n+1
to an integer:
boolean[] isPrime = new boolean[(int) (n + 1)];
Now, you know the theory, you should realize that implementing a sieve for long
s like this isn't going to work, since you will not have enough memory and Java simply doesn't allow you to make arrays of sizes bigger than 2^31-1. So, just change everything in your method to int
. This would look like this:
public static boolean[] primeSieve(int n)
{
boolean[] isPrime = new boolean[n + 1];
for (int i = 2; i <= n; i++)
isPrime[i] = true;
for (int i = 2; i*i <= n; i++)
if (isPrime[i])
for (int j = i; i*j <= n; j++)
isPrime[i * j] = false;
return isPrime;
}
And to optimize the memory usage for big sieves, I'd recommend using a java.util.BitSet
:
public static BitSet primeSieve(int n)
{
BitSet isPrime = new BitSet(n+1);
for (int i = 2; i <= n; i++)
isPrime.set(i);
for (int i = 2; i*i <= n; i++)
if (isPrime.get(i))
for (int j = i; i*j <= n; j++)
isPrime.set(i * j, false);
return isPrime;
}