I am using the Sieve of Eratosthenes algorithm to find the prime numbers in a range (from a min value to a max value). However, I cannot seem to get it to work if I include a min value.
Here is my code in Java:
protected static List<Integer> getSievePrimes(int a, int b) {
List<Integer> primeNumbers = new ArrayList();
boolean [] isComposite = new boolean [b + 1];
isComposite[1] = true;
// Mark all composite numbers
for (int i = 2; i <= b; i++) {
// for (int i = a == 1 ? 2 : a; i <= b; i++) {
if (!isComposite[i]) {
// 'i' is a prime number
//if (i >= a) {
primeNumbers.add(i);
//}
int multiple = 2;
while (i * multiple <= b) {
isComposite [i * multiple] = true;
multiple++;
}
}
}
return primeNumbers;
}
As you can see it currently only caters for the max value (b
), and not the min value (a
).
Question
How can I modify the method above to cater for both min and max?