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 is not a prime number.
3 is a pernicious number, as the number of set bits in it is
Given a number
n, find out whether it’s a pernicious number or not.
n = 5
5is a pernicious number.
n = 15
15is 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")
countSetBitsthat calculates the number of set bits in a given number.
isPrimethat states whether a given number is a prime number or not.
nthat we want to check.
nas the number and get the number of set bits in
isPrimefunction. Then, we print the result to the console.
View all Courses