Given two integers ‘L’ and ‘R’, write a program to find the total numbers that are having prime number of set bits in their binary representation in the range [L, R].
Input : l = 6, r = 10 Output : 4 Explanation : 6 -> 110 (2 set bits, 2 is prime) 7 -> 111 (3 set bits, 3 is prime) 9 -> 1001 (2 set bits, 2 is prime) 10 -> 1010 (2 set bits, 2 is prime) Hence count is 4 Input : l = 10, r = 15 Output : 5 10 -> 1010 (2 set bits, 2 is prime) 11 -> 1011 (3 set bits, 3 is prime) 12 -> 1100 (2 set bits, 2 is prime) 13 -> 1101 (3 set bits, 3 is prime) 14 -> 1110 (3 set bits, 3 is prime) Hence count is 5
Explanation: In this program we find a total number, that’s having prime number of set bit. so we use a CPP predefined function __builtin_popcount() these functions provide a total set bit in number. as well as be check the total bit’s is prime or not if prime we increase the counter these process repeat till given range.
Time Complexity : Let’s n = (r-l)
so overall time complexity is N*sqrt(N)
We can optimize above solution using Sieve of Eratosthenes.
- Prime Number of Set Bits in Binary Representation | Set 2
- Number of mismatching bits in the binary representation of two integers
- Binary representation of next number
- Binary representation of a given number
- Count number of trailing zeros in Binary representation of a number using Bitset
- Check if the binary representation of a number has equal number of 0s and 1s in blocks
- Binary representation of previous number
- Next greater number than N with exactly one bit different in binary representation of N
- Largest number with binary representation is m 1's and m-1 0's
- Number of leading zeros in binary representation of a given number
- Find the n-th number whose binary representation is a palindrome
- Check if binary representation of a number is palindrome
- Occurrences of a pattern in binary representation of a number
- Find consecutive 1s of length >= n in binary representation of a number
- Sum of decimal equivalent of all possible pairs of Binary representation of a Number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Mithun Kumar