// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
// run with -Xmx300m
public class Primes {
    private final static int[] MASK = { 1, 2, 4, 8, 16, 32, 64, 128 };
    private static boolean isBitSet(byte[] b, int ix) {
        int bytix = ix >> 4;
        int bitix = (ix & 0x0F) >> 1;
        return (b[bytix] & MASK[bitix]) > 0;
    }
    private static void setBit(byte[] b, int ix) {
        int bytix = ix >> 4;
        int bitix = (ix & 0x0F) >> 1;
        b[bytix] |= MASK[bitix];
    }
    private static void findPrimes(int n) {
        long t1 = System.currentTimeMillis();
        byte[] b = new byte[n / 16 + 1];
        int sqrtn = (int)Math.sqrt(n);
        for(int i = 3; i <= sqrtn; i += 2) {
            if(!isBitSet(b, i)) {
                for(int j = 3 * i; j <= n && j > 0; j += (2 * i)) {
                    setBit(b, j);
                }
            }
        }
        int nprim = 1;
        for(int k = 3; k <= n && k > 0; k += 2) {
            if(!isBitSet(b, k)) {
                nprim++;
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println(nprim + " primes in " + n + " numbers - found in " + (t2 - t1) / 1000.0 + " seconds");
    }
    public static void main(String[] args) {
        findPrimes(100000);
        // for reasons unknown to me it does not work with Integer.MAX_VALUE if -server is used
        findPrimes(Integer.MAX_VALUE - 1);
    }
}
