Prime Number of Set Bits in Binary Representation

Given two integers left and right, return how many numbers in the inclusive range [left, right] have a prime number of set bits (1 bits) in their binary representation.

30:00

Prime Number of Set Bits in Binary Representation
easy
Free written solution
Topics
Companies

Given two integers left and right, return how many numbers in the inclusive range [left, right] have a prime number of set bits (1 bits) in their binary representation.

Example 1:
Input: {"left":6,"right":10}
Output: 4
Constraints:
  • 1≤left≤right≤1061 \leq left \leq right \leq 10^6

  • 0≤right−left≤1040 \leq right - left \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"left":6,"right":10}

A number has at most 20 set bits here, so the only primes that matter are 2, 3, 5, 7, 11, 13, 17 and 19. Mark them as bits of one mask: 665772.

x = – in binary

range [6, 10]

set bits = ?

mask = 665772: bit k is 1 when k is prime

0

20

▲

1

19

▲

0

18

▲

1

17

▲

0

16

▲

0

15

▲

0

14

▲

1

13

▲

0

12

▲

1

11

▲

0

10

▲

0

9

▲

0

8

▲

1

7

▲

0

6

▲

1

5

▲

0

4

▲

1

3

▲

1

2

▲

0

1

▲

0

0

▲

checked 0 of 5

count = 0

nothing yet

x:bits, green = prime count of 1s

Variables
VariableValue
mask665772
DepthFunction Call
Stack empty
0/12