Note: Version 2, below, uses the Sieve of Eratosthenes. There are several answers that helped with what I originally asked. I have chosen the Sieve of Era
I have a really efficient implementation:
BitSet, requiring only one bit per number.initialCapacity for the Array appropriately.Here's the code:
public ArrayList sieve(int n) {
int upperBound = (int) (1.25506 * n / Math.log(n));
ArrayList result = new ArrayList(upperBound);
if (n >= 2)
result.add(2);
int size = (n - 1) / 2;
BitSet bs = new BitSet(size);
int i = 0;
while (i < size) {
int p = 3 + 2 * i;
result.add(p);
for (int j = i + p; j < size; j += p)
bs.set(j);
i = bs.nextClearBit(i + 1);
}
return result;
}