In this section, we will learn about the evil number and the java program on evil numbers. We will write java code to check the given number for evil number.
What is Evil Number?
A number is said to be an evil number if it is a positive whole number that has an even number of 1’s in its binary expansion. Binary expansion refers to the binary representation of a number that is with 0(zero) and 1(one).
Odious numbers are opposite to evil numbers.
Example of evil number:
Input = 3
The binary value of 3 = 11. Since the 1’s are even, therefore 3 is an evil number.
Input = 23
The binary value of 23 = 10111. Since the 1’s are even, therefore 23 is an evil number.
Input = 4
The binary value of 4 = 100. Since the 1’s are odd, therefore 23 is not an evil number. But it is an odious number.
Now we know what is Evil number is, let us see Evil Number Program in Java with source code.
Java program to check whether the given number is an evil number or not.
We will take a number and find its binary equivalent and store the binary value in a variable. Then we will check the number of 1’s present in that binary variable. If the number of 1’s is even then it is an evil number else the given number is not an evil number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import java.util.Scanner; public class EvilNumberProgram { // user-defined method to check evil number public static boolean isEvil(int number) { // calling binaryConversion function by passing the number long binValue = binConversion(number); int count = 0; // iteration to increase the count value on every 1's while (binValue != 0) { if (binValue % 10 == 1) count++; binValue /= 10; } // check for count for even value if (count % 2 == 0) return true; // if odd value than return false return false; } private static long binConversion(int num) { long binValue = 0; int remainder = 0; int i = 1; //iteration to convert the number into binary while (num != 0) { remainder = num % 2; binValue += remainder * i; num /= 2; i *= 10; } return binValue; } public static void main(String[] args) { // declaration of variables int num = 0; Scanner scan = new Scanner(System.in); System.out.print("Enter the positive number: "); num = scan.nextInt(); // check the condition of returned value for evil number if (isEvil(num)) System.out.println(num + " is an evil number"); else System.out.println(num + " is not an evil number"); } } |
Output: Evil Number Java.
//Run 1
Enter the positive number: 23
23 is an evil number
//Run 2
Enter the positive number: 4
4 is not an evil number
In the above java evil program, we created two user-defined functions, one for the conversion of an integer to binary and another one that checks the number of 1’s present in the binary number and returns the true-false value to the main function accordingly.