I have a bitSet and I want to turn off all the multiples of a given index.
eg: given a bitset -- > {1, 2, 3, 5, 7, 9, 11, 13, 15, 17}, I want to iterate through the bitset and turn off the multiples of each of them. In the end, I should have {1,2,3,5,7,11,13,17} which are nothing but prime numbers. so far I have:
public static void getPrimeNumbers(int n) {
BitSet s = new BitSet();
// s.set(0);
s.set(1);
s.set(2);
//create the set having all numbers till n
for (int i = 3; i <= n; i += 2) {
s.set(i);
}
//for element in Bitset ....
//need to clear multiple of bits in iteration
}
need a little help here, I should be able to pick up from there..
you could do some thing like this:
or you can look at the next turned bit and turn off all its multiples:
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 butsievelogic, more details you can find in wiki.