The problem is stated as follows:
Given two integers left
and right
, return the count of numbers in the range [left, right]
(inclusive) having a prime number of set bits in their binary representation.
[left, right]
?
To solve this problem, follow these steps:
[left, right]
, count the set bits and check if that count is prime.def countPrimeSetBits(left: int, right: int) -> int:
def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i = 5
while (i * i) <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
# Precompute the set of all primes up to 19
prime_set = {i for i in range(2, 20) if is_prime(i)}
result = 0
for num in range(left, right + 1):
set_bits = bin(num).count('1')
if set_bits in prime_set:
result += 1
return result
is_prime
function runs in (O(\sqrt{p})) time.bin(num).count('1')
runs in (O(\log n)) where (n) is the number being converted.[left, right]
, which runs (O(n)) where (n = \text{right} - \text{left} + 1).Overall time complexity is approximately (O(n \cdot \log n + \sqrt{p})) where (n) is the range size and (p) the largest number of set bits we need to check for primality.
print(countPrimeSetBits(6, 10)) # Output: 4
This counts numbers 6 to 10 and checks the set bits:
Hence, we get 4 numbers with a prime number of set bits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?