Neil Morris wrote:
> I rang the following code for finding prime numbers the results I got
> for my computer is
> 105097565 prime numbers
> 2147483629 being the highest
> 13:31:14 taken 13 hours 31 minutes and 14 seconds
This reminds me of the mid 1980's and playing with Macro-32.
See code below for one way of doing it.
Arne
================================================== ==
// 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);
}
}