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 floorMod
and the normal modulo operation are the same.
If the dividend and divisor are of different signs, then the result of floorMod
has 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.floorMod
method 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;
The fractional representation is .
floorDiv(23, 4) = 5
floorMod(23, 4) = 23 - ( 5 * 4 ) = 23 - 20 = 3
The fractional representation is .
floorDiv(-23, 4) = -6
floorMod(-23, 4) = -23 - ( -6 * 4 ) = -23 - (-24) = -23 + 24 = 1
The fractional representation is .
floorDiv(23, -4) = -6
floorMod(23, -4) = 23 - ( -6 * -4 ) = 23 - 24 = 23 - 24 = -1
The fractional representation is .
floorDiv(-23, -4) = 5
floorMod(-23, -4) = -23 - ( 5 * -4 ) = -23 - (-20) = -23 + 20 = -3
public static int floorMod(int x, int y)
int x
: dividendint y
: divisorMath.floorMod()
returns the floor modulus.
public static int floorMod(long x, int y)
public static long floorMod(long x, long y)
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();}}