C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Warning: For negative odd numbers, the remainder will be -1 not 1. So we test for "not equal to zero" instead.
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
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
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