I think the way to do this is not to think of beetle as its numerical representation, as we usually do, but to think of it in a list of numbers. Therefore, the bit rate
1111
will represent the numbers 1, 2, 3 and 4. Now, if we say that a '1' represents a prime and a '0' represents not prime, we can make a sieve as follows.
Set all bits to 1 (I'm going to use 16 bits that represent integers from 1 to 16)
1111 1111 1111 1111
I know that one is not simple, so I set it to zero.
0111 1111 1111 1111
Now I know that the next meeting "1" I represent a prime number, but all the multiples of this number are not primary by definition, so I leave only one "1", but all its multiple values ββare equal to "0". Since the next " 1 "represents the number 2, I zero every second bit.
0110 1010 1010 1010
The advantage of this method over the others is that when I cross the remaining bits, I do not need to check each of them to see if it is divisible by 2 (therefore, nothing like this if i % 2 == 0 is required). I can just increase the index by 2, and I know that I will always land on non-simple.
Now I'm just doing the same thing again with the next β1β that I come across (the next prime, starting with the last first number that I identified, 2). I know this is simple, since it is not divisible by any of the numbers below. I know that all its multiples are prime, therefore, since it is in the third position, I set every third next bit to '0'. Some of them are already β0β, since they are also multiples of 2. This is good, just leave them β0β.
0110 1010 0010 1000
The next "1" that you come across is the fifth bit. Now you can keep going until you get to the end, but since 5 is more than the square root of the number of bits from which I started, I know that I will no longer collect composites, so I finished.
After a short search, I found a really good example of implementation in Deitel and Deitel C ++ How to Program . They also give good explanations of the algorithm and code.