MichaelJonnu
MichaelJonnu

Reputation: 41

How to set all of the values to true within a Boolean array at once?

I'm trying to create a program which will print out all the prime numbers between two numbers using the Sieve or Eratosthenes. I'm trying to follow the pseudocode on the website, but i'm slightly stuck on the first bit which says:

Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.

I've tried doing this and I came up with this: (I was going to use #DEFINE but the range at which the prime numbers will be printed at will be based on user input so different each time)

bool *prime = malloc((number1-1) * sizeof(*prime));

However I think this only sets the size and not the actual values in the array.

I did some research on this already and found similiar questions on here, but they were all for different programming languages.

Upvotes: 2

Views: 6057

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155363

First off, memset can be used to set a range of bytes to any value, so:

memset(prime, '\xff', (number1-1) * sizeof(*prime));

should set all bits to 1 in the array; any non-zero value is true, and \xff is the byte pattern of all 1s, so it's as truthy as any other non-zero value.

It looks like memset may be inappropriate here, so the only unambiguously correct solution with no changes to program logic is a straight loop:

for (size_t i = 0; i < number1-1; ++i) {
    primes[i] = true;
}

That said, there is a slightly more clever way to do this: Reverse the definition of the array. Instead of the array being true when prime, make it true when not prime. That way, initialization can simplify to:

bool *notprime = calloc(number1-1, sizeof(*prime));

Now you can benefit from the cheap zeroing calloc typically provides (when sieving large enough ranges that the OS is tapped for already zeroed memory) and avoid the need to initialize them to some other value at all.

Note: When you allocated the array, you wanted sizeof(*prime), not sizeof(prime); I fixed that in the equivalent calloc call.

Upvotes: 2

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

You can use memset. Usually 1 is defined as true and 0 as false.

memset(prime,1,n * sizeof(*prime));  

Another method is to use a for loop to initialize the array to 1

#include <stdbool.h>
for (int i=0; i<n; i++)
{
    prime[i] = true;   
}

Upvotes: 4

Related Questions