Prime Number of Set Bits in Binary Representation

easy bit-manipulation math

Problem

Count integers in [L, R] whose binary representation has a prime number of set bits. Since values are at most 1e6, set-bit counts are small.

InputL=6, R=10
Output4
6,7,9,10 have 2,3,2,2 set bits, all prime.

def countPrimeSetBits(L, R):
    primes = {2,3,5,7,11,13,17,19,23,29,31}
    return sum(1 for x in range(L, R+1) if bin(x).count('1') in primes)
function countPrimeSetBits(L, R) {
  const primes = new Set([2,3,5,7,11,13,17,19,23,29,31]);
  let ans = 0;
  for (let x = L; x <= R; x++) {
    let c = 0, y = x;
    while (y) { c += y & 1; y >>>= 1; }
    if (primes.has(c)) ans++;
  }
  return ans;
}
int countPrimeSetBits(int L, int R) {
    Set<Integer> primes = Set.of(2,3,5,7,11,13,17,19,23,29,31);
    int ans = 0;
    for (int x = L; x <= R; x++)
        if (primes.contains(Integer.bitCount(x))) ans++;
    return ans;
}
int countPrimeSetBits(int L, int R) {
    set<int> primes = {2,3,5,7,11,13,17,19,23,29,31};
    int ans = 0;
    for (int x = L; x <= R; x++)
        if (primes.count(__builtin_popcount(x))) ans++;
    return ans;
}
Time: O((R-L) log R) Space: O(1)