you could do some thing like this:
//you start from 3 because 1 and 2 are prime already
int i = 3;
//you can do square check, since you would have turned off all bits before you reach n
while (i * i < n) {
if (s.get(i)) {
int k = 3 * i;
while (k <= n) {
s.clear(k);
k += i;
}
}
i++;
}
or you can look at the next turned bit and turn off all its multiples:
for (int j = s.nextSetBit(3);j>=0;j=s.nextSetBit(j+1)){
int k =3 * j;
while (k <= n){
s.clear(k);
k+=j;
}
}
here, the nextsetBit would give you the next turned on bit at or after a specified index. you increment, every position, by a factor of bit index, so that all its turned off. In each while loop
, you are turning off the multiples of bit index. this is nothing but sieve
logic, more details you can find in wiki.