|
| 1 | +/** |
| 2 | + * @file count_distinct_primes_from_binary_string.cpp |
| 3 | + * @brief Count distinct primes formed from binary strings using allowed operations. |
| 4 | + * |
| 5 | + * @author Rudraksh Tank |
| 6 | + * @date July 2025 |
| 7 | + * |
| 8 | + * @details |
| 9 | + * Given a binary string, the task is to count how many distinct prime decimal numbers |
| 10 | + * can be formed by: |
| 11 | + * - Swapping any two characters (makes position irrelevant) |
| 12 | + * - Changing any '1' to '0' (not the reverse) |
| 13 | + * |
| 14 | + * Efficient solution using bit manipulation and Sieve of Eratosthenes. |
| 15 | + * |
| 16 | + * Tags: Bit Manipulation, Prime Numbers, Combinatorics, Greedy, Bitmask |
| 17 | + */ |
| 18 | + |
| 19 | +#include <iostream> |
| 20 | +#include <vector> |
| 21 | +#include <unordered_set> |
| 22 | +#include <algorithm> |
| 23 | + |
| 24 | +const int MAX = 1e6; |
| 25 | +std::vector<bool> is_prime; |
| 26 | + |
| 27 | +/** |
| 28 | + * @brief Precomputes prime numbers up to MAX using the Sieve of Eratosthenes. |
| 29 | + */ |
| 30 | +void precomputePrimes() { |
| 31 | + is_prime.assign(MAX + 1, true); |
| 32 | + is_prime[0] = is_prime[1] = false; |
| 33 | + for (int i = 2; i * i <= MAX; i++) { |
| 34 | + if (is_prime[i]) { |
| 35 | + for (int j = i * i; j <= MAX; j += i) { |
| 36 | + is_prime[j] = false; |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * @brief Counts distinct prime numbers that can be formed from the given binary string. |
| 44 | + * @param s Binary string input |
| 45 | + * @return Number of distinct primes possible after allowed transformations |
| 46 | + */ |
| 47 | +int countPrimeBinaryStrings(const std::string &s) { |
| 48 | + int n = s.length(); |
| 49 | + int k = std::count(s.begin(), s.end(), '1'); |
| 50 | + int cnt = 0; |
| 51 | + int limit = 1 << n; |
| 52 | + |
| 53 | + std::unordered_set<int> seen; |
| 54 | + |
| 55 | + for (int i = 2; i < limit; i++) { |
| 56 | + if (__builtin_popcount(i) <= k && is_prime[i]) { |
| 57 | + if (!seen.count(i)) { |
| 58 | + cnt++; |
| 59 | + seen.insert(i); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return cnt; |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * @brief Main function to test the algorithm. |
| 69 | + */ |
| 70 | +int main() { |
| 71 | + precomputePrimes(); |
| 72 | + std::string s; |
| 73 | + std::cin >> s; |
| 74 | + std::cout << countPrimeBinaryStrings(s) << std::endl; |
| 75 | + return 0; |
| 76 | +} |
| 77 | + |
0 commit comments