Prime Number of Set Bits in Binary Representation - Problem
Binary Detective Challenge: Given two integers 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 bits

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.

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
Prime Set Bits VisualizationRange [6, 10]:6110โ‚‚2 bitsPrime โœ“7111โ‚‚3 bitsPrime โœ“81000โ‚‚1 bitNot Prime โœ—Prime Numbers โ‰ค 32:2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31Optimization InsightSince max number is 10โถ,max set bits = logโ‚‚(10โถ) โ‰ˆ 20We can precompute all primesup to 32 for O(1) lookup!Result for [6,10]: Count = 4
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!
Asked in
Amazon 25 Google 18 Microsoft 12 Apple 8
28.6K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen