
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- Prime Number of Set Bits in Binary Representation in C++
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Check if binary representation of a number is palindrome in Python
- Get the number of bits in the exponent portion of the floating point representation in Python
- Binary representation of a given number in C++
- Print the number of set bits in each node of a Binary Tree in C++ Programming.
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Check if all bits of a number are set in Python
- Binary Number with Alternating Bits in C++
- Number of leading zeros in binary representation of a given number in C++
- Number of 1 Bits in Python
- Number of integers with odd number of set bits in C++
- Find the Number of 1 Bits in a large Binary Number in C++
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python

Advertisements