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].
Examples:
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.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( 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 ;
}
int primeBitsInRange( int l, int r)
{
int tot_bit, count = 0;
for ( int i = l; i <= r; i++) {
tot_bit = __builtin_popcount(i);
if (isPrime(tot_bit))
count++;
}
return count;
}
int main()
{
int l = 6, r = 10;
cout << primeBitsInRange(l, r);
return 0;
}
|
Java
import java.lang.*;
class GFG{
static boolean isPrime( 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 ;
}
static int primeBitsInRange( int l, int r)
{
int tot_bit, count = 0 ;
for ( int i = l; i <= r; i++) {
tot_bit = Integer.bitCount(i);
if (isPrime(tot_bit))
count++;
}
return count;
}
public static void main(String[] args)
{
int l = 6 , r = 10 ;
System.out.println(primeBitsInRange(l, r));
}
}
|
Python3
def isPrime(n):
if (n < = 1 ): return False ;
if (n < = 3 ): return True ;
if (n % 2 = = 0 or n % 3 = = 0 ):
return False ;
i = 5 ;
while (i * i < = n):
if (n % i = = 0 or n % (i + 2 ) = = 0 ):
return False ;
i = i + 6 ;
return True ;
def primeBitsInRange(l, r):
count = 0 ;
for i in range (l, r + 1 ):
tot_bit = bin (i).count( '1' );
if (isPrime(tot_bit)):
count + = 1 ;
return count;
l = 6 ;
r = 10 ;
print (primeBitsInRange(l, r));
|
C#
class GFG{
static int BitCount( int n)
{
int count = 0;
while (n != 0)
{
count++;
n &= (n - 1);
}
return count;
}
static bool isPrime( 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 ;
}
static int primeBitsInRange( int l, int r)
{
int tot_bit, count = 0;
for ( int i = l; i <= r; i++) {
tot_bit = BitCount(i);
if (isPrime(tot_bit))
count++;
}
return count;
}
public static void Main()
{
int l = 6, r = 10;
System.Console.WriteLine(primeBitsInRange(l, r));
}
}
|
Javascript
<script>
function BitCount(n)
{
count = 0;
while (n != 0)
{
count++;
n &= (n - 1);
}
return count;
}
function isPrime(n)
{
if (n <= 1)
return false ;
if (n <= 3)
return true ;
if (n % 2 == 0 || n % 3 == 0)
return false ;
for (i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false ;
return true ;
}
function primeBitsInRange(l, r)
{
var tot_bit, count = 0;
for (i = l; i <= r; i++)
{
tot_bit = BitCount(i);
if (isPrime(tot_bit))
count++;
}
return count;
}
var l = 6, r = 10;
document.write(primeBitsInRange(l, r));
</script>
|
PHP
<?php
function BitCount( $n )
{
$count = 0;
while ( $n != 0)
{
$count ++;
$n &= ( $n - 1);
}
return $count ;
}
function isPrime( $n )
{
if ( $n <= 1) return false;
if ( $n <= 3) return true;
if ( $n % 2 == 0 || $n % 3 == 0)
return false;
for ( $i = 5; $i * $i <= $n ; $i = $i + 6)
if ( $n % $i == 0 ||
$n % ( $i + 2) == 0)
return false;
return true;
}
function primeBitsInRange( $l , $r )
{
$count = 0;
for ( $i = $l ; $i <= $r ; $i ++)
{
$tot_bit = BitCount( $i );
if (isPrime( $tot_bit ))
$count ++;
}
return $count ;
}
$l = 6;
$r = 10;
echo primeBitsInRange( $l , $r );
?>
|
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
Approach#2: Using sieve of eratosthenes
The code uses three functions: sieve_of_eratosthenes(n), count_set_bits(n), and count_prime_set_bits(l, r). The first function, sieve_of_eratosthenes(n), generates a list of Boolean values indicating whether each integer up to n is prime or not. The second function, count_set_bits(n), returns the number of set bits (binary digits equal to 1) in the binary representation of n. The third function, count_prime_set_bits(l, r), counts the number of integers between l and r (inclusive) whose binary representations have a prime number of set bits. It does so by first using the sieve_of_eratosthenes function to generate a list of primes up to the maximum number of bits in any integer between l and r. It then iterates over each integer between l and r, counts the number of set bits in its binary representation using count_set_bits, and increments a counter if that count is a prime number. The final count is returned.
Algorithm
1. Generate all primes from 1 to the maximum number of set bits possible in the binary representation of r (let’s call it max_bits).
2. Loop from l to r (both inclusive).
3. Convert each decimal number to its binary representation.
4. Count the number of set bits in the binary representation.
5. Check if the count is prime or not using the pre-generated primes.
6. If the count is prime, increment the counter.
7. Return the counter as the answer.
C++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector< bool > sieve_of_eratosthenes( int n) {
vector< bool > primes(n+1, true );
primes[0] = primes[1] = false ;
for ( int i = 2; i <= sqrt (n); i++) {
if (primes[i]) {
for ( int j = i * i; j <= n; j += i) {
primes[j] = false ;
}
}
}
return primes;
}
int count_set_bits( int n) {
int count = 0;
while (n > 0) {
count += n % 2;
n /= 2;
}
return count;
}
int count_prime_set_bits( int l, int r) {
int max_bits = log2(r) + 1;
vector< bool > primes = sieve_of_eratosthenes(max_bits);
int count = 0;
for ( int i = l; i <= r; i++) {
if (primes[count_set_bits(i)]) {
count++;
}
}
return count;
}
int main() {
int l = 6;
int r = 10;
cout << count_prime_set_bits(l, r) << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
public static boolean [] sieveOfEratosthenes( int n) {
boolean [] primes = new boolean [n + 1 ];
Arrays.fill(primes, true );
primes[ 0 ] = primes[ 1 ] = false ;
for ( int i = 2 ; i <= Math.sqrt(n); i++) {
if (primes[i]) {
for ( int j = i * i; j <= n; j += i) {
primes[j] = false ;
}
}
}
return primes;
}
public static int countSetBits( int n) {
int count = 0 ;
while (n > 0 ) {
count += n % 2 ;
n /= 2 ;
}
return count;
}
public static int countPrimeSetBits( int l, int r) {
int maxBits = ( int ) (Math.log(r) / Math.log( 2 )) + 1 ;
boolean [] primes = sieveOfEratosthenes(maxBits);
int count = 0 ;
for ( int i = l; i <= r; i++) {
if (primes[countSetBits(i)]) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int l = 6 ;
int r = 10 ;
System.out.println(countPrimeSetBits(l, r));
}
}
|
Python3
from math import sqrt
def sieve_of_eratosthenes(n):
primes = [ True ] * (n + 1 )
primes[ 0 ] = primes[ 1 ] = False
for i in range ( 2 , int (sqrt(n)) + 1 ):
if primes[i]:
for j in range (i * i, n + 1 , i):
primes[j] = False
return primes
def count_set_bits(n):
count = 0
while n> 0 :
count + = n % 2
n / / = 2
return count
def count_prime_set_bits(l, r):
max_bits = len ( bin (r)) - 2
primes = sieve_of_eratosthenes(max_bits)
count = 0
for i in range (l, r + 1 ):
if primes[count_set_bits(i)]:
count + = 1
return count
l = 6
r = 10
print (count_prime_set_bits(l, r))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static List< bool > SieveOfEratosthenes( int n)
{
List< bool > primes = new List< bool >(n + 1);
for ( int i = 0; i <= n; i++)
primes.Add( true );
primes[0] = primes[1] = false ;
for ( int i = 2; i <= Math.Sqrt(n); i++)
{
if (primes[i])
{
for ( int j = i * i; j <= n; j += i)
{
primes[j] = false ;
}
}
}
return primes;
}
static int CountSetBits( int n)
{
int count = 0;
while (n > 0)
{
count += n % 2;
n /= 2;
}
return count;
}
static int CountPrimeSetBits( int l, int r)
{
int maxBits = ( int )Math.Log(r, 2) + 1;
List< bool > primes = SieveOfEratosthenes(maxBits);
int count = 0;
for ( int i = l; i <= r; i++)
{
if (primes[CountSetBits(i)])
{
count++;
}
}
return count;
}
static void Main()
{
int l = 6;
int r = 10;
Console.WriteLine(CountPrimeSetBits(l, r));
}
}
|
Javascript
function sieveOfEratosthenes(n) {
const primes = new Array(n + 1).fill( true );
primes[0] = primes[1] = false ;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (primes[i]) {
for (let j = i * i; j <= n; j += i) {
primes[j] = false ;
}
}
}
return primes;
}
function countSetBits(n) {
let count = 0;
while (n > 0) {
count += n % 2;
n = Math.floor(n / 2);
}
return count;
}
function countPrimeSetBits(l, r) {
const maxBits = Math.floor(Math.log2(r) + 1);
const primes = sieveOfEratosthenes(maxBits);
let count = 0;
for (let i = l; i <= r; i++) {
if (primes[countSetBits(i)]) {
count++;
}
}
return count;
}
const l = 6;
const r = 10;
console.log(countPrimeSetBits(l, r));
|
Time Complexity: O((r-l+1) * log log r), where log log r is the time complexity of sieve_of_eratosthenes.
Auxiliary Space: O(log log r)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 Oct, 2023
Like Article
Save Article