Prime Number of Set Bits in Binary Representation - Problem

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.

Recall that the number of set bits an integer has is the number of 1's present when written in binary.

For example, 21 written in binary is 10101, which has 3 set bits.

Input & Output

Example 1 — 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). So 4 numbers have prime set bits.
Example 2 — Small Range
$ Input: left = 10, right = 15
Output: 5
💡 Note: 10 = 1010₂ (2 bits), 11 = 1011₂ (3 bits), 12 = 1100₂ (2 bits), 13 = 1101₂ (3 bits), 14 = 1110₂ (3 bits), 15 = 1111₂ (4 bits, not prime). Numbers 10,11,12,13,14 have prime set bits.
Example 3 — Single Number
$ Input: left = 4, right = 4
Output: 0
💡 Note: 4 = 100₂ has 1 set bit, and 1 is not prime, so result is 0.

Constraints

  • 1 ≤ left ≤ right ≤ 106
  • 0 ≤ right - left ≤ 104

Visualization

Tap to expand
Prime Number of Set Bits INPUT Range: [left, right] left = 6 right = 10 Numbers: 6,7,8,9,10 6 = 110 (2 bits) 7 = 111 (3 bits) 8 = 1000 (1 bit) 9 = 1001 (2 bits) 10 = 1010 (2 bits) ALGORITHM STEPS 1 Precompute Primes primes = {2,3,5,7,11,13,17,19} 2 Loop Through Range for n in [left...right] 3 Count Set Bits Use popcount or bit ops 4 Check if Prime If bits in primes, count++ Check Results: 6: 2 bits - 2 is prime OK 7: 3 bits - 3 is prime OK 8: 1 bit - 1 not prime NO 9: 2 bits - 2 is prime OK 10: 2 bits - 2 is prime OK FINAL RESULT Numbers with prime set bits: 6 7 9 10 Excluded (1 bit not prime): 8 Output 4 Count of valid numbers {6, 7, 9, 10} = 4 numbers Key Insight: Since numbers up to 10^6 have at most 20 bits, we only need primes up to 20: {2, 3, 5, 7, 11, 13, 17, 19} Using a precomputed set of small primes allows O(1) lookup for each number's bit count. TutorialsPoint - Prime Number of Set Bits in Binary Representation | Precomputed Primes Approach
Asked in
Google 15 Facebook 12
28.5K Views
Medium Frequency
~15 min Avg. Time
985 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