Compute the floor of a division and modulus in Java

Write a program that computes the floor division and the floor modulus of the given dividend (x) and divisor (y).

Java program to compute the floor of a division and modulus

public class Main {

    public static void main(String[] args) {

        int x = -222;
        int y = 14;

        System.out.println("Dividend: " + x + " Divisor: " + y);
        
        System.out.println();
        int z = Math.floorDiv(x, y); // -222/14 = -15.85, so output is -16
        System.out.println("Floor division via '/' is: " + (x / y));
        System.out.println("Floor division via 'floorDiv()' is: " + z);

        System.out.println();
        int m = Math.floorMod(x, y); 
        System.out.println("Floor modulus vis '%' is: " + (x % y));
        System.out.println("Floor modulus via 'floorMod()' is: " + m);
    }

}

Output:

Dividend: -222 Divisor: 14

Floor division via '/' is: -15
Floor division via 'floorDiv()' is: -16

Floor modulus vis '%' is: -12
Floor modulus via 'floorMod()' is: 2

Comments