Last active
October 17, 2022 13:19
-
-
Save jsbonso/9d6099739be06720bdf95d9f8202f399 to your computer and use it in GitHub Desktop.
Simple Odd or Even Coding Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Simple Odd or Even Coding Example | |
Author: Jon Bonso | |
Demo Link: https://www.online-java.com/BYJCIjwhpg | |
Mathematical Theory: | |
- Parity is the property of an integer which determines if it is even or odd. | |
- An even number is an integer that can be divided exactly by 2 is an even number. | |
- An odd number is an integer that cannot be divided exactly by 2 and has a remainder | |
Examples of an even number (no remainder after dividing by 2): | |
-2 / 2 = -1 | |
0 / 2 = 0 | |
4 / 2 = 2 | |
Examples of an odd number (has a remainder after dividing by 2): | |
3 / 2 = 1.5 (this is also read as 1 Remainder 1 if a modulo operation (%) was used instead of (/) ) | |
5 / 2 = 2.5 (also considered as 2 Remainder 1) | |
7 / 2 = 3.5. (also considered as 3 Remainder 1) | |
As you can see above, an odd number is an integer that doesn't produce a | |
remainder (or a decimal) after being divided by the number 2 | |
Notes: | |
- The modulo operation (%) can be used to get the remainder of a division, if any. | |
*/ | |
public class OddOrEven | |
{ | |
/** | |
* Returns true if the input is an even number or | |
* false if the number is an odd number. | |
* | |
* This function uses a modulo operation to get the | |
* remainder of the division, after the input is divided by 2. | |
* | |
*/ | |
static boolean isEven(int i){ | |
return (i % 2) == 0; | |
} | |
public static void main(String[] args) { | |
System.out.println("Is the number -2 even? " + isEven(-2)); | |
System.out.println("Is the number -1 even? " + isEven(-1)); | |
System.out.println("Is the number 0 even? " + isEven(0)); | |
System.out.println("Is the number 1 even? " + isEven(1)); | |
System.out.println("Is the number 2 even? " + isEven(2)); | |
System.out.println("Is the number 3 even? " + isEven(3)); | |
System.out.println("Is the number 4 even? " + isEven(4)); | |
} | |
} |
Alternative solution via bit masking:
static boolean isEven(int i){
return (i & 1) == 0;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Odd Or Even Java Demo: https://www.online-java.com/BYJCIjwhpg