Friday, March 15, 2019

Modulo Operator: Java

Java has one important arithmetical operator you may not be familiar with, %, also known as the modulus or remainder operator. The % operator returns the remainder of two numbers. 

So 20 modulo 5 is 0 because 20 divided by 5 is 4 with no remainder.
    21 modulo 5 is 1 22 modulo 5 is 2 23 modulo 5 is 3 24 modulo 5 is 4 25 modulo 5 is 0
In C, C++ and Java, modulo is represented as the percent sign. So
    int a = 20 % 5 ;

The most common use case for the modulo operator is to find out if a given number is odd or even.
Modulo has a variety of uses. If you want to know if a number is an even "hundred", like 300, 400, 500 or 256700, you can test for it like this:
    if ( ( a % 100 ) == 0 )
    {
        System.out.println( a + "exactly!");
    }

If the outcome of the modulo operation between any number and two is equal to one, it’s an odd number:
1
2
3
4
@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1() {
    assertThat(3 % 2).isEqualTo(1);
}
On the other hand, if the result is zero (i.e. there is no remainder), it’s an even number:
1
2
3
4
@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0() {
    assertThat(4 % 2).isEqualTo(0);
}


No comments: