I want to find all the prime numbers under 10 billion. Which is 5 times as big as int can hold (which is the limitation of arrays regardless of type). Attempting to allocate over 1.2billion at a time results in out of heap space error. I tried using List instead of a boolean array, but the set element method for arrayLists only indexes up to int. What bugs me, is that pretty quickly into the sieve there are less than an integer number of elements not crossed off. One method that should work, would be to create a partition of 10 arrays and smash them together... but that would be ugly. Let me know if you have any suggestions of an elegant way to solve this. (Other than using Python lol). I already have an n^2/2 brute force implementation, but that takes a long time to run so really I want to solve this as big O fast as possible. My Sieve implementation that works up to 1.2Billion is as follows:
public class SieveEratosthenes {
private boolean[] nums;
public static void main(String[] args) {
int n = 1000000;
SieveEratosthenes s = new SieveEratosthenes(n);
for(int i=0;i<s.nums.length;i++){
if(s.nums[i]){
System.out.println(i);
}
}
}
public SieveEratosthenes(int max){
sieve(max);
}
private boolean[] sieve(int max){
nums = new boolean[max+1];
initFlags();
for(int i=2;i*i<max;i++){
for(int j=i*i;j<=max;j+=i){//cross off non-primes
nums[j]=false;
}
}
return nums;
}
private void initFlags(){
if(nums != null&&nums.length>1){
nums[0]=false;
nums[1]=false;
nums[2]=true;
}
for(int i=3;i<nums.length;i++){
nums[i]=true;
}
}
public List<Long> sieveToList(){
List<Long> sieveList = new ArrayList();
for(int i=0;i<nums.length;i++){
if(nums[i]){
sieveList.add((long)i);
}
}
return sieveList;
}