Java Odd and Even Numbers: Modulo Division

This Java program determines if numbers are odd or even. It uses modulo division and handles negative numbers.
Odd, even numbers. All integers have a parity: they are even or odd. Numbers like 1 and 3 are odd, and 0 and 2 are even. This can be computed with a simple Java method.
Modulo division. With a modulo division, we determine if a number evenly divides into another. In this way we tell if a number can be divided by 2 evenly—it is then even.

Warning: For negative odd numbers, the remainder will be -1 not 1. So we test for "not equal to zero" instead.

Example program. Let us examine the program. We introduce two static methods, isEven and isOdd. We could implement isOdd by returning "!isEven" but this does not simplify the program.

Boolean: The methods isEven and isOdd return booleans—true or false—based on the parity of the argument int.

Java program that tests for odd, even numbers public class Program { public static boolean isEven(int value) { // An even number is always evenly divisible by 2. return value % 2 == 0; } public static boolean isOdd(int value) { // This handles negative and positive odd numbers. return value % 2 != 0; } public static void main(String[] args) { // Test our implementation. int value = 100; if (isEven(value)) { System.out.println(value); } value = 99; if (isOdd(value)) { System.out.println(value); } } } Output 100 99
Negative, odd numbers. Years ago I implemented a flawed isOdd method. It tested for a remainder of 1, so would always return false on negative numbers. This was a negative event in my life.

Here: I test the isOdd method for negative odd numbers and it is correct. IsEven does not have a similar issue.

Java program that tests negative odd numbers public class Program { public static boolean isOdd(int value) { // Same implementation as above. return value % 2 != 0; } public static void main(String[] args) { // Test positive and negative numbers for odd parity. for (int i = -5; i <= 5; i++) { if (isOdd(i)) { System.out.println(i); } } } } Output -5 -3 -1 1 3 5
Research. I like Wikipedia. In the page about parity on Wikipedia, we find that odd numbers are simply those that are not even. This matches the implementations in the above programs.

Thus: An isOdd method could correctly be equal to "!isEven." But this would not simplify our Java code.

Quote: Parity is a mathematical term that describes the property of an integer's inclusion in one of two categories: even or odd. An integer is even if it is "evenly divisible" by two and odd if it is not even.

Parity, mathematics: Wikipedia
A summary. For games and simulators, a fast test for a number's parity can be useful. Other programs may also benefit from this code. We implemented and tested odd and even tests.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls