Prime Number of Set Bits in Binary Representation in C++


In this problem, we are given two integers L and R. Our task to print the total numbers that have set bits counting to a prime number that is in between L to R.

Let’s take an example to understand the problem

Input: L = 7, R = 12
Output: 6
Explanation:
7 -> 111 , set bits = 2, prime number.
8 -> 1000 , set bits = 1, not prime number.
9 -> 1001 , set bits = 2, prime number
10 -> 1010 , set bits = 2, prime number
11 -> 1011, set bits = 3, prime number
12 -> 1100, set bits = 2, prime number

To solve this problem, we will traverse each and every element within the range. And check the total number of set bits in the number, for this we will use a predefined function in CPP _builtin_popcount(). Then, we will check the set bits of the number for prime. If yes increase count otherwise not.

Program to show the implementation of our solution

Example

 Live Demo

#include <iostream>
using namespace std;
bool isPrimeNumber(int n) {
   if (n <= 1) return false;
   if (n <= 3) return true;
   if (n%2 == 0 || n%3 == 0) return false;
   for (int i=5; i*i<=n; i=i+6)
   if (n%i == 0 || n%(i+2) == 0)
   return false;
   return true;
}
void printPrimeSetBits(int l, int r) {
   int tot_bit, count = 0;
   for (int i = l; i <= r; i++) {
      tot_bit = __builtin_popcount(i);
      if (isPrimeNumber(tot_bit))
         count++;
   }
   cout<<count;
}
int main() {
   int L = 7, R = 13;
   cout<<"Total numbers with prime set bits between "<<L<<" and "<<R<<" are : ";
   printPrimeSetBits(L, R);
   return 0;
}

Output

Total numbers with prime set bits between 7 and 13 are : 6

Updated on: 03-Feb-2020

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements