Your decision is not a sieve of Eratosthenes. This is obvious because you are using the modulo operator in your code; the correct sieve of Eratosthenes uses only the addition in the internal circuit, and not division or modulo. Here is a simple version of the Eratosthenes sieve that imports the BitSet and LinkedList from java.util and returns a LinkedList of primes less than n:
public static LinkedList sieve(int n) { BitSet b = new BitSet(n); LinkedList ps = new LinkedList(); b.set(0,n); for (int p=2; p<n; p++) { if (b.get(p)) { ps.add(p); for (int i=p+p; i<n; i+=p) { b.clear(i); } } } return ps; }
The basic idea is to create a sieve ( BitSet b) with each element originally set to Prime (represented as a set bit), iterating through a sieve that searches and reports each next prime sheet, and when one is hit, all of it multiple of the sieve, marking it Composite (represented as a cleared bit). Multipliers are detected by adding, not dividing, and the inner loop consists only of addition, the operation of clearing bits, comparing to find the end of the sieve and go to the beginning of the loop, so it is very fast.
Optimization options are available that make the Eratosthenes sieve run even faster, but that should be enough to get you started. When you're ready for more, I modestly recommend this essay on my blog.
If you need prime numbers in a range that doesn't start from zero, you need a segmented strainer from Eratosthenes. I discussed the Eratosthenes segmented sieve earlier on Stack Overflow, and also discuss it on my blog.
source share