Математический метод floorMod () в Java

Опубликовано: 13 Февраля, 2022

Java.lang.Math.floorMod () - это встроенная математическая функция в java, которая возвращает модуль пола переданных ей целочисленных аргументов. Следовательно, модуль нижнего этажа равен (a - (floorDiv (a, b) * b)) , имеет тот же знак, что и делитель b, и находится в диапазоне -abs (b) <t <+ abs (b) .

Взаимосвязь между floorDiv и floorMod:

floorDiv(a, b) * b + floorMod(a, b) == a

Разница в значениях между floorMod и оператором% связана с разницей между floorDiv, который возвращает целое число, меньшее или равное частному, и оператором /, который возвращает целое число, наиболее близкое к нулю.

Синтаксис:

public static int floorMod(data_type a, data_type b)

Parameters: The function accepts two parameters.

  • a: This refers to the dividend value.
  • b: This refers to the divisor value.

    The parameters can be of data-type int or long.

Exception: It throws an ArithmeticException if the divisor is zero.

Return Value: This method returns the floor modulus x – (floorDiv(x, y) * y).

Below programs are used to illustrate the working of java.lang.Math.floorMod() method.
Program 1:

// Java program to demonstrate working
// of java.lang.Math.floorMod() method
import java.lang.Math;
  
class Gfg1 {
  
    public static void main(String args[])
    {
        int a = 25, b = 5;
        System.out.println(Math.floorMod(a, b));
  
        // Divisor and dividend is having same sign
        int c = 123, d = 50;
        System.out.println(Math.floorMod(c, d));
  
        // Divisor is having negative sign
        int e = 123, f = -50;
        System.out.println(Math.floorMod(e, f));
  
        // Dividend is having negative sign
        int g = -123, h = 50;
        System.out.println(Math.floorMod(g, h));
    }
}
Output:
0
23
-27
27

Program 2:

// Java program to demonstrate working
// of java.lang.Math.floorMod() method
import java.lang.Math;
  
class Gfg2 {
  
    public static void main(String args[])
    {
        int x = 200;
        int y = 0;
  
        System.out.println(Math.floorMod(x, y));
    }
}

Output:

Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at java.lang.Math.floorDiv(Math.java:1052)
    at java.lang.Math.floorMod(Math.java:1139)
    at Gfg2.main(File.java:13)

Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int-

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.