I'm working on a method in Java which creates boolean array isPrime:
boolean[] isPrime;
in which prime numbers are labeled with 'true' and the rest with 'false'.
While I'm at it I'd also like to count the number of Primes found:
int numPrimesFound;
The basic idea is to use the Sieve of Eratosthenes. So far my method looks like this:
public Sieve(final int limit) {
long startTime = System.currentTimeMillis();
boolean[] isPrime = new boolean[limit];
this.isPrime = isPrime;
for (int i=3; i<=limit ;i+=2) {
isPrime[i] = true; //sets all even numbers to true
}
isPrime[2] = true;
numPrimesFound = 1; //special case of '2'
for (int i = 3; i * i <= limit; i += 2) {
if (isPrime[i] == true) {
for (int j = i; i * j <= limit; j += 2) {
isPrime[i * j] = false; //has a multiple ==> not a prime
numPrimesFound++; //doesn't work yet
}
}
}
long stopTime = System.currentTimeMillis(); //measuring execution time
System.out.println("Sieve: " + (stopTime - startTime) + " milliseconds.")
}
So my problem is that
numPrimesFound++:
doesn't work because the sieve sets the value of some non-prime numbers to 'false' more than once (e.g. 45 bcs 3*15 = 45 and 9*5 = 45).
So does anybody have a clue on how I could rewrite this program so it sets all the non-prime numbers to 'false' only once?
Or generally speaking, can anybody suggest ways to make the method faster?