Home » Pernicious Number in Java

Pernicious Number in Java

by Online Tutorials Library

Pernicious Number in Java

In this section, we will discuss what is pernicious number and also create Java programs to check if the given number is a pernicious number or not. The pernicious number program frequently asked in Java coding interviews and academics.

Pernicious Number

If the total number of 1’s in the binary representation of a number is a prime number, then that number is called a pernicious number. A pernicious number is always a positive integer.

Example of Pernicious Number

1 is not a pernicious number. It is because the binary representation of 1 is 1, and 1 is not a prime number.

2 is not a pernicious number. It is because the binary representation of 2 is 1 0. The total number of 1’s in the binary representation of 2 is 1, and 1 is not the prime number.

3 is a pernicious number. It is because the binary representation of 3 is 1 0 1. The total number of 1’s in the binary representation of 3 is 2, and 2 is a prime number.

4 is not a pernicious number. It is because the binary representation of 4 is 1 0 0. The total number of 1’s in the binary representation of 4 is 1, and 1 is not the prime number.

5 is a pernicious number. It is because the binary representation of 5 is 1 0 1. The total number of 1’s in the binary representation of 5 is 2, and 2 is a prime number.

Steps to find the Pernicious Number

Step 1: Take a number and find its binary representation by dividing the number continuously by 2.

Step 2: Store the binary representation of the number in an array.

Step 3: Take a counter and initialize it with 0

Step 4: Using a loop, move across each element of the array. If the element is 1, increment the value of the counter by 1; otherwise, not.

Step 5: Check the value of the counter and find out whether the value of the counter is odd or even.

Step 6: If the value is odd, the number taken in step 1 is a pernicious number; otherwise, not.

Pernicious Number Java Program

The following example will use loops to find the pernicious numbers using the steps defined above.

FileName: PerniciousNumberExample1.java

Output:

1 is not the pernicious number.  2 is not the pernicious number.  3 is the pernicious number.  4 is not the pernicious number.  5 is the pernicious number.  6 is the pernicious number.  7 is the pernicious number.  8 is not the pernicious number.  9 is the pernicious number.  10 is the pernicious number.  11 is the pernicious number.  12 is the pernicious number.  13 is the pernicious number.  14 is the pernicious number.  15 is not the pernicious number.  16 is not the pernicious number.  17 is the pernicious number.  18 is the pernicious number.  19 is the pernicious number.  20 is the pernicious number.  

Next TopicCohesion in Java

You may also like