Odious Number in Java: Definition, Rules, Examples, and Practice Problems
An Odious Number is a positive integer whose binary representation contains an odd number of 1s. These numbers are the opposite of Evil Numbers and are frequently used in number theory puzzles and coding challenges.
What Is an Odious Number?
A number is called an Odious Number if:
- You convert the number to binary.
- Count the number of 1s in its binary form.
- If the count is odd, the number is an Odious Number.
Example:
- 7 → binary is 111 → contains 3 ones → Odious Number
- 10 → binary is 1010 → contains 2 ones → not an Odious Number
- 13 → binary is 1101 → contains 3 ones → Odious Number
Why Is It Called an Odious Number?
Odious Numbers are named in contrast to Evil Numbers. While Evil Numbers have an even count of 1s, Odious Numbers have an odd count. The names were chosen playfully by early mathematicians studying binary patterns.
Java Program to Check Odious Number
Below is a Java program that checks whether a number is an Odious Number:
import java.util.Scanner;
public class OdiousNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
String binary = Integer.toBinaryString(num);
int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}
if (count % 2 != 0) {
System.out.println(num + " is an Odious Number");
} else {
System.out.println(num + " is NOT an Odious Number");
}
}
}
Examples
| Number | Binary | Count of 1s | Odious Number? |
|---|---|---|---|
| 7 | 111 | 3 | Yes |
| 13 | 1101 | 3 | Yes |
| 10 | 1010 | 2 | No |
| 5 | 101 | 2 | No |
3 Practice Challenges
Challenge 1: Manual Binary Conversion
Write a Java program to check if a number is an Odious Number without using built-in binary conversion methods.
Challenge 2: Count Odious Numbers
Given 10 numbers as input, count how many are Odious Numbers.
Challenge 3: Range Generator
Write a Java program to print all Odious Numbers between 1 and 1000.