I'm trying to calculate all prime numbers of given a limit using the sieve of eratosthenes method. I know how to do that with big numbers as limit, but what if I try a real big number, larger than long type? I know I could use BigInteger but the problem is I don't know how to set a size of a boolean array(see the code) as BigInteger.
import java.util.ArrayList;
import java.util.Arrays;
public class Eratosthenes {
private ArrayList<Integer> primes;
private Integer limit;
public Eratosthenes(Integer limit) {
this.limit = limit;
this.primes = new ArrayList<Integer>();
}
void sieve() {
boolean[] allNumbers = new boolean[this.limit];
Arrays.fill(allNumbers, Boolean.TRUE);
for (int p = 2; (p * p) <= this.limit; p++)
if (allNumbers[p] == true)
for (int i = (p * 2); i < this.limit; i += p)
allNumbers[i] = false;
for (int p = 2; p < this.limit; p++)
if (allNumbers[p])
this.primes.add(p);
}
void showResult() {
System.out.println("[" + this.limit + "] primes: " + this.primes.size());
}
}
public class Main {
public static void main(String[] args) {
Eratosthenes eratostenes = new Eratosthenes(Integer.parseInt(args[0]));
eratostenes.sieve();
eratostenes.showResult();
}
}