c - Sieve of Eratosthenes using a bit array -
i have bit array prime[]
of unsigned int
. wish implement sieve of eratosthenes using array, having each bit represent number n
. is, given n
, array element holds bit corresponds n
prime[n/32]
, specific bit in position n%32
.
my testbitis0(int n)
function returns 1 when number prime (if bit == 0), otherwise 0:
return ( (prime[n/32] & (1 << (n%32) )) != 0);
my setbit(int n)
function sets bit 1 @ corresponding position:
int = n/32; int pos = n%32; unsigned int flag = 1; flag = flag << pos; prime[i] = prime[i] | flag;
the issue i'm having when call setbit
multiples of prime number, don't think sets bit correctly. when call setbit
multiples of prime number (such 4, 6, 8, etc. number 2) next time run line:
if(testbitis0(i)) { ... }
with i = 4/6/8/etc
still return 1 when should return 0.
can please check code make sure implementing correctly? thanks.
this looks you're after. there's bit array , bit twiddling functions too.
Comments
Post a Comment