Problem Description
Given two integers left
and right
, return the count of numbers in the inclusive range [left, right]
having a prime number of set bits in their binary representation.
Key Insights
- The number of set bits in an integer can be found using bit manipulation.
- A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
- Precompute prime numbers up to a certain limit using the Sieve of Eratosthenes to efficiently check if the count of set bits is prime.
- The maximum possible set bits for numbers up to 10^6 is limited since 10^6 in binary has at most 20 bits.
Space and Time Complexity
Time Complexity: O(n log log n) for prime computation and O(m) for checking each number in the range, where n is the upper limit for the sieve and m is the count of numbers in the range. Space Complexity: O(n) for storing prime numbers.
Solution
To solve the problem, we will:
- Use a Sieve of Eratosthenes to precompute prime numbers up to 20, since the maximum number of set bits for numbers up to 10^6 is 20.
- Iterate through each number in the range
[left, right]
, count the number of set bits, and check if that count is prime. - Maintain a count of numbers whose set bits are prime and return this count.