Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

bitwise

What are pernicious numbers?

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. πŸ’ͺ

Overview

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.

Example 1:

  • Input: n = 5
  • Output: 5 is a pernicious number.

Example 2:

  • Input: n = 15
  • Output: 15 is not a pernicious number.

Solution

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

  1. We find the count of set bits in the given number.
  2. 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.

Example

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")

Explanation

  • 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

bitwise

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