Ravi

Tired of LeetCode? π©

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πͺ

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.

- Input:
`n = 5`

- Output:
`5`

is a pernicious number.

- Input:
`n = 15`

- Output:
`15`

is not a pernicious number.

The solution is quite straightforward. These are the steps we follow to figure out the solution:

- We find the count of set bits in the given number.
- We check whether the count of set bits obtained from step 1 is a prime number or not.

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 = 0while n:n = n & (n - 1)count+=1return countdef isPrime(inp):if inp == 1: return Falsefor n in range(2,int(inp**0.5)+1):if inp % n==0:return Falsereturn Truen = 15set_bit_count = countSetBits(n)if isPrime(set_bit_count):print(n, " is a pernicious number")else:print(n, " is not a pernicious number")

- Lines 1β6: We define a function called
`countSetBits`

that calculates the number of set bits in a given number. - Lines 8β14: We define a function called
`isPrime`

that states whether a given number is a prime number or not. - Line 17: We define the number
`n`

that we want to check. - Line 18: We invoke the
`countSetBits()`

function with`n`

as the number and get the number of set bits in`n`

. - Lines 19β22: We check whether the result in line 18 is a prime number or not by invoking the
`isPrime`

function. Then, we print the result to the console.

RELATED TAGS

CONTRIBUTOR

Ravi

Tired of LeetCode? π©

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πͺ

Keep Exploring

Related Courses