0

I found this code here on StackOverflow:

public static BitSet computePrimes(int limit) {
    final BitSet primes = new BitSet();
    primes.set(0, false);
    primes.set(1, false);
    primes.set(2, limit, true);
    for (int i = 0; i * i < limit; i++) {
        if (primes.get(i)) {
            for (int j = i * i; j < limit; j += i) {
                primes.clear(j);
            }
        }
    }
    return primes;
}

but I'm struggling to understand how to get it working above Integer.MAX_VALUE.

I know i have to use long, but what do I have to change (in the loops) in this method to get Primes from Integer.MAX_VALUE to 3037000499L, or is it even possible?

phil330d
  • 31
  • 1
  • 4
  • 1
    *but I'm struggling to understand how to get it working above Integer.MAX_VALUE.* You should struggle, because it is not possible. All the relevant methods of BitSet take `int` arguments for bit indexes, so you can't exceed `Integer.MAX_VALUE`. You could write your own implementation of a bit set that accepts `long` arguments for bit indexes, and then your bit set could be as large as your implementation allows. – President James K. Polk Jun 03 '19 at 02:11
  • You could try this implementation of BitSet that uses `long` values as indexes: http://java-performance.info/bit-sets/ – Erwin Bolwidt Jun 03 '19 at 02:24
  • But here's the thing. While the `long` implementation of `BitSet` will take you beyond 2^31, you will still run into an OOME limit at somewhere between 2 to 4 times the max heap size. And that will (should!) be less than your RAM size. If you want to go further, your algorithm will need to be smarter. – Stephen C Jun 03 '19 at 03:31
  • One option is to only hold odd numbers in your BitSet, which will effectively double the number of primes you can hold. Beyond that you could use a segmented sieve, where you split the BitSet into smaller pieces, each piece after the first starting above zero. – rossum Jun 03 '19 at 11:16
  • Note that 3037000499L is between 2\*\*31 and 2\*\*32. A simple implementation would be to use two BitSets, the first taking indices between 0 and Integer.MAX_VALUE inclusive, and the second from Integer.MAX_VALUE + 1 through 3037000499L inclusive. – President James K. Polk Jun 03 '19 at 13:07

0 Answers0