Prime Number of Set Bits in Binary Representation in Python

Suppose we have two integers L and R, we have to find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary form.

So, if the input is like L = 6 and R = 10, then the output will be 4, as there are 4 numbers 6(110),7(111),9(1001),10(1010), all have prime number of set bits.

To solve this, we will follow these steps −

• count := 0
• for j in range L to R, do
• if set bit count of j is in [2,3,5,7,11,13,17,19], then
• count := count + 1
• return count

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
def countPrimeSetBits(self, L, R):
def popcount(i):
return bin(i)[2:].count('1')
count = 0
for j in range(L,R+1):
if popcount(j) in [2,3,5,7,11,13,17,19]:
count +=1
return count
ob = Solution()
print(ob.countPrimeSetBits(6,10))

Input

6,10

Output

4