|
16 | 16 | * Tags: Bit Manipulation, Prime Numbers, Combinatorics, Greedy, Bitmask
|
17 | 17 | */
|
18 | 18 |
|
19 |
| -#include <bit> |
20 |
| -#include <iostream> |
21 |
| -#include <vector> |
22 |
| -#include <unordered_set> |
23 |
| -#include <algorithm> |
| 19 | +#include <bit> ///< For std::popcount (bit manipulation utilities) |
| 20 | +#include <iostream> ///< For input/output stream handling (std::cin, std::cout) |
| 21 | +#include <vector> ///< For dynamic array storage (std::vector) |
| 22 | +#include <unordered_set>///< For storing distinct primes without duplicates (std::unordered_set) |
| 23 | +#include <algorithm> ///< For algorithms like std::count |
| 24 | +#include <cassert> ///< For assert-based testing |
24 | 25 |
|
25 |
| -const int MAX = 1e6; |
| 26 | +const uint32_t MAX = 1e6; ///< Upper bound for prime sieve |
26 | 27 | static std::vector<bool> is_prime;
|
27 | 28 |
|
28 | 29 | /**
|
29 | 30 | * @namespace bit_manipulation
|
30 |
| - * @brief Bit manipulation algorithms |
| 31 | + * @brief Bit manipulation algorithms and prime preprocessing |
31 | 32 | */
|
32 | 33 | namespace bit_manipulation {
|
33 | 34 |
|
| 35 | + /** |
| 36 | + * @brief Precomputes all prime numbers up to MAX using Sieve of Eratosthenes. |
| 37 | + */ |
34 | 38 | void precomputePrimes() {
|
35 | 39 | is_prime.assign(MAX + 1, true);
|
36 | 40 | is_prime[0] = is_prime[1] = false;
|
37 |
| - for (int i = 2; i * i <= MAX; i++) { |
| 41 | + for (uint32_t i = 2; i * i <= MAX; i++) { |
38 | 42 | if (is_prime[i]) {
|
39 |
| - for (int j = i * i; j <= MAX; j += i) { |
| 43 | + for (uint32_t j = i * i; j <= MAX; j += i) { |
40 | 44 | is_prime[j] = false;
|
41 | 45 | }
|
42 | 46 | }
|
@@ -67,17 +71,26 @@ namespace bit_manipulation {
|
67 | 71 |
|
68 | 72 | return cnt;
|
69 | 73 | }
|
70 |
| - |
71 |
| - void tests(){ |
72 |
| - precomputePrimes(); |
73 |
| - std::string s; |
74 |
| - std::cin >> s; |
75 |
| - std::cout << countPrimeBinaryStrings(s) << std::endl; |
76 |
| - } |
77 |
| - |
78 |
| -} //bit manipulation |
| 74 | + |
| 75 | +} // namespace bit_manipulation |
| 76 | + |
| 77 | +/** |
| 78 | + * @brief Static test function using assertions instead of I/O. |
| 79 | + */ |
| 80 | +static void tests() { |
| 81 | + using namespace bit_manipulation; |
| 82 | + |
| 83 | + precomputePrimes(); |
| 84 | + |
| 85 | + // Example test cases |
| 86 | + assert(countPrimeBinaryStrings("1") == 0); // Only "1" -> not prime |
| 87 | + assert(countPrimeBinaryStrings("11") > 0); // Should form primes like 3 |
| 88 | + assert(countPrimeBinaryStrings("101") > 0); // Can form primes like 5 |
| 89 | + assert(countPrimeBinaryStrings("000") == 0); // No 1s -> no primes possible |
| 90 | +} |
| 91 | + |
79 | 92 | /**
|
80 |
| - * @brief Main function to test the algorithm. |
| 93 | + * @brief Main function to run tests. |
81 | 94 | */
|
82 | 95 | int main() {
|
83 | 96 | tests();
|
|
0 commit comments