Prime Number of Set Bits in Binary Representation - Problem
Binary Detective Challenge: Given two integers
What are set bits? The number of 1's when a number is written in binary. For example:
โข
โข
Goal: Return the count of numbers whose set bit count is a prime number (2, 3, 5, 7, 11, 13, ...).
Example: For range [6, 10], we check each number's binary representation and count set bits, then determine if that count is prime.
left and right, count how many numbers in the inclusive range [left, right] have a prime number of set bits (1's) in their binary representation.What are set bits? The number of 1's when a number is written in binary. For example:
โข
21 in binary is 10101, which has 3 set bitsโข
6 in binary is 110, which has 2 set bitsGoal: Return the count of numbers whose set bit count is a prime number (2, 3, 5, 7, 11, 13, ...).
Example: For range [6, 10], we check each number's binary representation and count set bits, then determine if that count is prime.
Input & Output
example_1.py โ Basic Range
$
Input:
left = 6, right = 10
โบ
Output:
4
๐ก Note:
6โ110(2 bits, prime), 7โ111(3 bits, prime), 8โ1000(1 bit, not prime), 9โ1001(2 bits, prime), 10โ1010(2 bits, prime). Total: 4 numbers with prime set bits.
example_2.py โ Small Range
$
Input:
left = 10, right = 15
โบ
Output:
5
๐ก Note:
10โ1010(2 bits, prime), 11โ1011(3 bits, prime), 12โ1100(2 bits, prime), 13โ1101(3 bits, prime), 14โ1110(3 bits, prime), 15โ1111(4 bits, not prime). Total: 5 numbers.
example_3.py โ Single Number
$
Input:
left = 1, right = 1
โบ
Output:
0
๐ก Note:
1โ1(1 bit). Since 1 is not a prime number, the result is 0.
Constraints
- 1 โค left โค right โค 106
- The maximum number of set bits is at most 32 (since 232 > 106)
- Key insight: We only need to check primality for numbers up to 32
Visualization
Tap to expand
Understanding the Visualization
1
Convert to Binary
Transform each number to its binary representation
2
Count Set Bits
Count the number of 1's in the binary string
3
Check Prime
Determine if the count is a prime number
4
Accumulate Result
Add to counter if prime, continue to next number
Key Takeaway
๐ฏ Key Insight: Since we're limited to 32 bits maximum, we can precompute all prime numbers up to 32 and use bit manipulation tricks for O(1) set bit counting, making the solution very efficient!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code