Returning the flooring/ceiling modulus – Text blocks, Locales, Numbers & Math
By Adenike Adekola / May 20, 2024 / No Comments / Exams of Java, Getting integral and fractional parts from a double, Java Certifications
23. Returning the flooring/ceiling modulus
Having the dividend / divisor = quotient computation, we know that the floor operation applied to the (dividend, divisor) pair returns the largest integer that is less than or equal to the algebraic quotient. By the largest integer, we understand the integer closest to positive infinity. Starting with JDK 8, this operation can be obtained via Math.floorDiv(). And, starting with JDK 18, Math.floorDivExact().On the other hand, the ceil operation applied to the (dividend, divisor) pair returns the smallest integer that is greater than or equal to the algebraic quotient. By the smallest integer, we understand the integer closest to negative infinity. Starting with JDK 18, this operation can be obtained via Math.ceilDiv() and Math.ceilDivExact().More details are in Problem 19.Now, based on the floor and ceil operations, we can define the following floor/ceil modulus relationships:
Floor_Modulus = dividend –
(floorDiv(dividend, divisor) * divisor)
Ceil_Modulus = dividend –
(ceilDiv(dividend, divisor) * divisor)
So, we can write this in code as:
int dividend = 162;
int divisor = 42; // 162 % 42 = 36
int fd = Math.floorDiv(dividend, divisor);
int fmodJDK8 = dividend – (fd * divisor); // 36
int cd = Math.ceilDiv(dividend, divisor);
int cmodJDK18 = dividend – (cd * divisor); // -6
Starting with JDK 8, floor modulus can be obtained via Math.floorMod() as follows:
int dividend = 162;
int divisor = 42;
int fmodJDK8 = Math.floorMod(dividend, divisor); // 36
Here, we use floorMod(int dividend, int divisor). But we can also use two more flavors: floorMod(long dividend, long divisor), and from JDK 9, floorMod(long dividend, int divisor).If the dividend % divisor is 0 then floorMod() is 0. If dividend % divisor and floorMod() are not 0 then their result differs only if the signs of the parameters differ.Starting with JDK 18, ceil modulus can be obtained via Math.ceilMod() as follows:
int cmodJDK18 = Math.ceilMod(dividend, divisor); // -6
Here, we use ceilMod(int dividend, int divisor). But we can also use two more flavors: ceilMod(long dividend, int divisor) and ceilMod(long dividend, long divisor).If the dividend % divisor is 0 then ceilMod() is 0. If dividend % divisor and ceilMod() are not 0 then their result differ only if the signs of the parameters are the same.Moreover, the relationship between floorMod() and floorDiv() is as follows:
dividend == floorDiv(dividend, divisor) * divisor
+ floorMod(dividend, divisor)
And, the relationship between ceilMod() and ceilDiv() is as follows:
dividend == ceilDiv(dividend, divisor) * divisor
+ ceilMod(dividend, divisor)
Notice that if the divisor is 0 then both, floorMod() and ceilMod() throw ArithmeticException.