My goal is to Turn off, or set to false, all array spots that are not prime. Array is provided as a parameter.
public static boolean[] sieveOfEratosthenes(boolean [] a){
int increment= 2;
for(int n = 0; n < 9; n++){
for(int i = increment; i < a.length; i += increment){
a[i] = false;
}
increment += 1;
}
a[2] = true;
a[3] = true;
a[5] = true;
a[7] = true;
return a;
}
Code works fine, I’m just wondering if there is a more efficient way than using:
a[2] = true;
a[3] = true;
a[5] = true;
a[7] = true;
to reset those array items as true.
Thanks in advance!
A good way to do this is to start your loop at iteration * 2. So your loop looks like this
This way you skip the first one.
Second modify your outer loop so that it ignores values that are already false because its prime factors took care of its products.
Now your loop looks like this
Third to handle any size array loop over your array for your increment value
This current loop assumes one and zero are considered prime. So set
a[0] = a[1] = false;to reflect the fact that 0 and 1 are not prime.