What is the Math.floorMod method in Java?
floorMod is a static method of the Math class that returns the floor modulus of the two numbers passed to it. The sign of the return value is the same as the sign of the passed divisor.
The formula to calculate floorMod is as follows:
floorMod(dividend, divisor) = dividend - (floorDiv(dividend, divisor) * divisor)
-
If the dividend and divisor are of the same sign, then the results of
floorModand the normal modulo operation are the same. -
If the dividend and divisor are of different signs, then the result of
floorModhas the same sign of the divisor.
The relationship between floorMod and floorDiv is as follows:
floorDiv(dividend, divisor) * divisor + floorMod(dividend, divisor) == dividend
The
Math.floorModmethod is introduced in Java 8.
The floorMod method is defined in the Math class, which is defined in the java.lang package.
To import the Math class, use the statement below:
import java.lang.Math;
Example 1
- dividend - 23
- divisor - 4
The fractional representation is .
floorDiv(23, 4) = 5floorMod(23, 4) = 23 - ( 5 * 4 ) = 23 - 20 = 3
Example 2
- dividend - -23
- divisor - 4
The fractional representation is .
floorDiv(-23, 4) = -6floorMod(-23, 4) = -23 - ( -6 * 4 ) = -23 - (-24) = -23 + 24 = 1
Example 3
- dividend - 23
- divisor - -4
The fractional representation is .
floorDiv(23, -4) = -6floorMod(23, -4) = 23 - ( -6 * -4 ) = 23 - 24 = 23 - 24 = -1
Example 4
- dividend - -23
- divisor - -4
The fractional representation is .
floorDiv(-23, -4) = 5floorMod(-23, -4) = -23 - ( 5 * -4 ) = -23 - (-20) = -23 + 20 = -3
Method signature
public static int floorMod(int x, int y)
Parameters
int x: dividendint y: divisor
Return value
Math.floorMod() returns the floor modulus.
Overloaded methods
public static int floorMod(long x, int y)
public static long floorMod(long x, long y)
Code
import java.lang.Math;public class Main{public static void main(String[] args){int dividend = 23;int divisor = 4;int remainder = Math.floorMod(dividend, divisor);System.out.printf("floorMod(%d, %d) = %d", dividend, divisor, remainder);System.out.println();dividend = 23;divisor = -4;remainder = Math.floorMod(dividend, divisor);System.out.printf("floorMod(%d, %d) = %d", dividend, divisor, remainder);System.out.println();dividend = -23;divisor = 4;remainder = Math.floorMod(dividend, divisor);System.out.printf("floorMod(%d, %d) = %d", dividend, divisor, remainder);System.out.println();dividend = -23;divisor = -4;remainder = Math.floorMod(dividend, divisor);System.out.printf("floorMod(%d, %d) = %d", dividend, divisor, remainder);System.out.println();}}