Prime Number of Set Bits in Binary Representation

Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.

Example:

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)

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int countSetBits(int n)
{
    int cnt = 0;
    while (n > 0)
    {
        n = n & (n - 1);
        cnt++;
    }
    return cnt;
}
int countPrimeSetBits(int Lint R)
{

    bool prime[1000001];
    memset(primetruesizeof(prime));
    prime[0] = false;
    prime[1] = false;
    for (int i = 2i * i <= 1000000i++)
    {
        if (prime[i])
        {
            for (int j = i * ij <= 1000000j += i)
            {
                prime[j] = false;
            }
        }
    }
    int ans = 0;
    for (int i = Li <= Ri++)
    {
        int cnt = countSetBits(i);
        if (prime[cnt])
        {
            ans++;
        }
    }
    return ans;
}

int main()
{
    int L = 6R = 10;

    cout << countPrimeSetBits(LR);

    return 0;
}


No comments:

Post a Comment