Evil Number in Java

In this blog, we will learn the meaning of Duck Number in Java and other related information. Let’s begin with the blog on Duck Number in Java. 

What is the Evil Number in Java?

Evil numbers are a fascinating concept in mathematics and computer science. In the realm of number theory, an evil number is a non-negative integer that has an even number of 1s in its binary representation. On the other hand, numbers with an odd number of 1s in their binary representation are known as odious numbers.

Know the Palindrome Program in Java here!

Examples of Duck Numbers in Java include:

To understand evil numbers better, let’s consider a few examples. The number 3, when represented in binary, is 11. Since it has an odd number of 1s (in this case, 2), it is an odious number. In contrast, the number 4 in binary is 100, which contains only one 1. Hence, 4 is an evil number.

Java program to find whether a given number is an Evil number or not.

//import required classes and packages  
import java.util.*;   
import java.io.*;   
import java.util.Scanner;  
  
//create EvilNumberExample class to check whether the given number is an Evil number or not  
public class EvilNumEx {  
  
    // create checkNumber() method that returns true when it founds number Evil   
    public static boolean evilnum(int n) {  
  
        // find the equivalence binary number using user defined convertToBinary() method  
        long binaryNumber = convertToBinary(n);  
  
        // find total number of 1's in binary number  
        int count = 0;  
  
        // iterate each digit of binary number  
        while(binaryNumber != 0) {  
  
            // if the last digit of binary number is 1, increase the count value  
            if(binaryNumber % 10 == 1)   
                count++;  
  
            // remove the last digit from the number  
            binaryNumber = binaryNumber / 10;  
        }  
  
        // check whether the value of count is even or odd  
        if(count % 2 == 0)  
            return true;    //return true when the value of count is even  
  
        //return false if the value of the count is false  
        return false;  
    }  
  
    //create convertToBinary() method to convert the decimal value into binary  
    private static long convertToBinary(int number) {  
        long binaryNumber = 0;  
        int rem = 0;  
        int j = 1;  
        while(number != 0) {  
            rem = number % 2;  
            binaryNumber += rem * j;  
            number = number / 2;  
            j = j * 10;  
        }  
          
        return binaryNumber;    //return the binary equivalent number of the decimal number  
    }  
      
    //main() method start  
    public static void main(String[] args) {  
      
        // declare variable in which the user entered value will be store  
        int n = 0;  
  
        // create scanner class object   
        Scanner sc =  new Scanner(System.in);  
          
        //display custom message  
        System.out.print("Enter a number : ");  
          
        //get input from user  
        n = sc.nextInt();  
  
        // check whether the number is evil number or not  
        if(evilnum(n))  
            System.out.println(n + " is an evil number");  
        else  
            System.out.println(n + " is not an evil number");  
  
    }  
} 

Explanation of the code:

Java program that checks whether a given number is an Evil number or not. Here’s a breakdown of the code and its explanation:

  • Importing Required Classes and Packages:

The code imports the necessary classes and packages required for input/output operations and user input.

  • EvilNumEx Class Definition:

The code defines a public class named EvilNumEx to encapsulate the functionality related to evil numbers.

  • evilnum() Method:

This method takes an integer n as a parameter and returns a boolean value indicating whether n is an evil number or not.

  • convertToBinary() Method:

This private method converts a decimal number into its binary equivalent. It takes an integer number as a parameter and returns the binary representation as a long.

  • Check Number for Evilness:

In this section, the code calls convertToBinary() to obtain the binary representation of the input number n. It then counts the number of ‘1’ bits in the binary representation using the count variable. If the count is even, the method returns true, indicating that the number is an evil number. Otherwise, it returns false.

  • convertToBinary() Implementation:
  • The convertToBinary() method converts a decimal number to its binary representation. It uses a loop to repeatedly divide the number by 2, obtaining the remainder at each step. The remainder is used to construct the binary representation by multiplying it with a position factor j and adding it to the binaryNumber. Finally, the method returns the resulting binary number.
  • Main Method:

The main() method is the entry point of the program. It prompts the user to enter a number and reads it using a Scanner object. It then calls the evilnum() method to check whether the entered number is an evil number or not. Finally, it displays the appropriate message based on the result.

Overall, the code demonstrates a simple implementation to determine whether a given number is an evil number using the binary representation and counting the number of ‘1’ bits.

Also, learn about Strong Number in Java here!

Output:

Enter a number : 17
17 is an evil number

Java program that finds and prints all the Evil numbers within a given range

//import required classes and packages  
import java.util.*;   
import java.io.*;   
import java.util.Scanner;  
  
//create a class to get all the Evil number in a given range  
public class FindEvilNum {  
  
    //main() method start  
    public static void main(String args[])  
    {  
        int range;  
          
        //create scanner class object  
        Scanner sc=new Scanner(System.in);  
          
        //show custom message  
        System.out.println("Enter the value of range");  
          
        //store user entered value into variable range  
        range = sc.nextInt();  
  
        for(int i = 1; i <= range; i++)  
            if(checkNumber(i)){  
                System.out.println(i + " is an Evil number");  
            }  
    }  
      
    // create checkNumber() method that returns true when it founds number Evil   
    public static boolean checkNumber(int num) {  
  
        // find the equivalence binary number using user defined convertToBinary() method  
        long binaryNum = convertToBinary(num);  
  
        // find total number of 1's in binary number  
        int count = 0;  
  
        // iterate each digit of binary number  
        while(binaryNum != 0) {  
  
            // if the last digit of binary number is 1, increase the count value  
            if(binaryNum % 10 == 1)   
                count++;  
  
            // remove the last digit from the number  
            binaryNum = binaryNum / 10;  
        }  
  
        // check whether the value of count is even or odd  
        if(count % 2 == 0)  
            return true;    //return true when the value of count is even  
  
        //return false if the value of the count is false  
        return false;  
    }  
  
    //create convertToBinary() method to convert the decimal value into binary  
    private static long convertToBinary(int number) {  
        long binaryNum = 0;  
        int rem = 0;  
        int j = 1;  
        while(number != 0) {  
            rem = number % 2;  
            binaryNum += rem * j;  
            number = number / 2;  
            j = j * 10;  
        }  
          
        return binaryNum;    //return the binary equivalent number of the decimal number  
    }  
} 

Explanation of the code:

The provided code is a Java program that finds and prints all the Evil numbers within a given range. Here’s an explanation of the code:

  • Importing Required Classes and Packages:

The code imports the necessary classes and packages required for input/output operations and user input.

  • FindEvilNum Class Definition:

The code defines a public class named FindEvilNum to encapsulate the functionality related to finding evil numbers.

  • Main Method:

The main() method is the entry point of the program. It prompts the user to enter the range value and reads it using a Scanner object. It then iterates from 1 to the given range and checks each number using the checkNumber() method. If a number is found to be an evil number, it is printed to the console.

  • checkNumber() Method:

The checkNumber() method takes an integer num as a parameter and returns a boolean value indicating whether num is an evil number or not. It follows the same logic as explained earlier to determine if the count of ‘1’ bits in the binary representation is even or odd.

  • convertToBinary() Method:

The convertToBinary() method converts a decimal number to its binary representation. It follows the same logic as explained earlier to obtain the binary representation of the input number.

Overall, the code allows the user to enter a range value and then iterates through the numbers from 1 to the given range. For each number, it checks if it is an evil number using the checkNumber() method and prints the evil numbers to the console.

Output:

Enter the value of range
20
3 is an Evil number
5 is an Evil number
6 is an Evil number
9 is an Evil number
10 is an Evil number
12 is an Evil number
15 is an Evil number
17 is an Evil number
18 is an Evil number
20 is an Evil number

10 Tips & Tricks for Evil Numbers in Java

This section presents ten tips and tricks to help you effectively implement evil numbers in Java as follows:

  • Understand the Concept:

Before diving into the implementation, ensure you have a solid understanding of what evil numbers are. An evil number is a non-negative integer with an even number of ‘1’ bits in its binary representation.

  • Binary Conversion:

To work with evil numbers, you’ll frequently need to convert integers to binary representations. Use the Integer.toBinaryString() method to convert an integer into a binary string.

  • Counting the Number of ‘1’ Bits:

Implement a function that counts the number of ‘1’ bits in a binary string. You can iterate through the string and increment a counter for each ‘1’ encountered.

  • Check Evil Number Status:

Create a function that determines whether a given number is evil or not. Use the count of ‘1’ bits in the binary representation to determine if it is even or odd. If the count is even, it is an evil number; otherwise, it is not.

  • Efficient Bit Counting:

To improve performance, consider using bitwise operations to count the number of ‘1’ bits in a binary string. Utilize bitwise AND operations and shift to iterate through each bit.

  • Input Validation:

When accepting user input, validate it to ensure it is a valid non-negative integer. Check for negative numbers or non-numeric characters to prevent errors in subsequent calculations.

  • Error Handling:

Implement appropriate error-handling mechanisms in your code. Handle potential exceptions, such as input format errors or arithmetic overflows, gracefully to maintain the stability of your program.

  • Optimize Performance:

If you’re working with large numbers, optimize your code for performance. Consider using bitwise operations, memoization, or other algorithmic techniques to reduce unnecessary computations and improve runtime efficiency.

  • Utilize Test Cases:

Develop comprehensive test cases to verify the correctness of your evil number implementation. Include both evil and non-evil numbers as input to ensure your code handles them correctly.

  • Documentation and Comments:

Throughout your code, provide clear and concise documentation and comments. Explain the purpose and functionality of each method, class, and variable to make your code easier to understand and maintain.

Get complete Java Programming Exercises and Solutions here!

Java’s implementation of evil numbers requires understanding, effective bit-counting, input validation, and error handling. We hoped that our blog post on “Evil Number in Java” would be informative and aid in your learning of Java programming. Visit our website Newtum to find more such coding-related blogs and courses, and keep learning with us!

About The Author

Leave a Reply