floorMod() int in Java

floorMod(): This method is available in the Math class of Java.

Syntax:

int java.lang.Math.floorMod(int x, int y)

This method takes two arguments of type int. This method returns the floor modulus of the int arguments.

The floor modulus is x - (floorDiv(x, y)*y),has the same sign as the divisor y, and is in the range of -abs(y) < r < +abs(y).

Examples: 

1. If the signs of the arguments are the same, the results of floorMod and the % operator are the same.floorMod(+4, +3) == +1; and (+4 %+3) == +1 ◦floorMod(-4, -3) == -1; and (-4 % -3) == -1

2.If the signs of the arguments are different, the results differ from the % operator. ◦floorMod(+4, -3) == -2; and (+4 % -3) == +1 ◦floorMod(-4, +3) ==+2; and (-4 % +3) == -1

Note: 

1.If the signs of arguments are unknown and a positive modulus is needed it can be computed as (floorMod(x, y) + abs(y)) % abs(y). 

2.The relationship between floorDiv and floorMod is such that

floorDiv(x, y) * y + floorMod(x, y) == x

Parameters: Two parameters are required for this method.

x: the dividend.

y: the divisor.

the floor modulus x - (floorDiv(x, y) * y)

Throws: ArithmeticException - if the divisor y is zero.

Approach

Java

public class FloorModInt {
    public static void main(String[] args) {

        int x = 17, y = 7;
        System.out.println(Math.floorMod(x, y));

    }
}

Output:

3

No comments:

Post a Comment