A pernicious number is a positive number whose count of set bits in its binary form is prime. All powers of 2 are not pernicious numbers because the number of set bits in such numbers is 1
and 1
is not a prime number.
For example, 3
is a pernicious number, as the number of set bits in it is 2
.
Given a number n
, find out whether it’s a pernicious number or not.
n = 5
5
is a pernicious number.n = 15
15
is not a pernicious number.The solution is quite straightforward. These are the steps we follow to figure out the solution:
For step 1, refer to the How to find the number of set bits in an integer shot.
For step 2, refer to the How do you check if a number is prime in Python? shot.
def countSetBits(n): count = 0 while n: n = n & (n - 1) count+=1 return count def isPrime(inp): if inp == 1: return False for n in range(2,int(inp**0.5)+1): if inp % n==0: return False return True n = 15 set_bit_count = countSetBits(n) if isPrime(set_bit_count): print(n, " is a pernicious number") else: print(n, " is not a pernicious number")
countSetBits
that calculates the number of set bits in a given number.isPrime
that states whether a given number is a prime number or not.n
that we want to check.countSetBits()
function with n
as the number and get the number of set bits in n
.isPrime
function. Then, we print the result to the console.RELATED TAGS
CONTRIBUTOR
View all Courses