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);
}


Friday, September 28, 2018

JavaScript Map Function

How does JavaScript Map Function work....

Here is an example

var numbers = [4, 9, 16, 25];

function myFunction() {
    x = document.getElementById("demo")
    x.innerHTML = numbers.map(Math.sqrt);
}

If I execute the above function as part of my Javascript it print

2,3,4,5

So what happened using map function I applied the Math.sqrt to every element of my numbers array.