sieve of erastothenes - initialize big bit array in C

99 Views Asked by At

So I'm trying to implement the sieve of Erastothenes using a bit array in C. I've tried manually setting the bits using

    int x;
    int i;

    x = x | (1 << i);    // Set bit position i in x 

However, I realized this will be too much iterations when I'm doing 10,000 iterations. If I use a 32-bit unsigned int array for my bit array, how do I initialize all 32 bits at once?

I tried setting

unsigned int[] arr = { [0-100000] = 1 };

that obviously didn't work.

4

There are 4 best solutions below

0
Fred On

Set the value of the 32bit unsigned int to 4294967295 or, if the number is a signed 32bit int set it to -1

11111111111111111111111111111111 <- 32 1's I used this site to convert it to decimal. https://www.rapidtables.com/convert/number/binary-to-decimal.html

1
Chris Dodd On

For an unsigned value with all bits set, use ~0U.
For type like uintmax_t, use something like ~(uintmax_t)0

0
dbush On

The simplest thing to do would be to use memset:

unsigned int arr[100000];
memset(arr, 0xff, sizeof arr);
0
chux - Reinstate Monica On

If I use a 32bit unsigned int array for my bit array, how do I initialize all 32 bits at once?

The below initializes all 10,000 elements of the array arr_not[] to zero.

uint32_t arr_not[10000]  = { 0 };

To use in OP's code, reverse the sense of a cleared bit to mean 1 in the original algorithm.

Standard C does not well support a way to initialize all the bits to 1 for such a large array.


Otherwise simply code as below to assign all the bits of arr[] to 1.

uint32_t arr[10000];
memset(arr, UCHAR_MAX, sizeof arr);