|
BDE 4.14.0 Production release
|
Provide an STL-compliant bitset class.
Canonical header: bsl_bitset.h
This component is for internal use only. Please include <bsl_bitset.h> instead and use bsl::bitset directly. This component implements a static bitset class that is suitable for use as an implementation of the std::bitset class template.
This section illustrates intended use of this component.
Suppose we want to write a function to determine whether or not a given number is prime. One way to implement this function is by using what's called the Sieve of Eratosthenes. The basic idea of this algorithm is to repeatedly walk the sequence of integer values and mark any numbers up to and including the particular value of interest that are integer multiples of first 2, then 3, then 5, etc. (skipping 4 because it was previously marked when we walked the sequence by 2's). Once we have walked the sequence with all primes up to and including the square root of the number of interest, we check to see if that number has been marked: If it has, it's composite; otherwise it's prime.
When implementing this classic algorithm, we need an efficient way of representing a flag for each potential prime number. The following illustrates how we can use bsl::bitset to accomplish this result, provided we know an upper bound on supplied candidate values at compile time.
First, we begin to define a function template that will determine whether or not a given candidate value is prime:
Then, we declare a bsl::bitset, compositeFlags, that will contain flags indicating whether a value corresponding to a given index is known to be composite (true) or is still potentially prime (false) up to and including the compile-time constant template parameter, MAX_VALUE.
Next, we observe that a default-constructed bsl::bitset has no flags set, We can check this by asserting that the none method returns true, by asserting that the any method returns false, or by asserting that the count of set bits is 0:
Then, we note that a bsl::bitset has a fixed size (the set can't be grown or shrunk) and verify that size is the same as the template argument used to create the bsl::bitset:
Next, we compute sqrt(candidate), which is as far as we need to look:
Now, we loop from 2 to sqrtOfCandidate, and use the sieve algorithm to eliminate non-primes:
Notice that if we don't return false from the loop, none of the lower numbers evenly divided the candidate value; hence, it is a prime number.
Finally, we can exercise our isPrime function with an upper bound of 10,000: