22. Computing the largest/smallest value that is less/greater than or equal to the algebraic quotient
By the largest value, we understand the value closest to positive infinity, while by the smallest value, we understand the value closest to negative infinity.
Computing the largest value that is less than or equal to the algebraic quotient can be done, starting with JDK 8, via floorDiv(int x, int y)
and floorDiv(long x, long y)
. Starting with JDK 9, we also have floorDiv(long x, int y)
.
Computing the smallest value that is greater than or equal to the algebraic quotient can be done, starting with JDK 18, via ceilDiv(int x, int y)
, ceilDiv(long x, int y)
, and ceilDiv(long x, long y)
.
However, none of these functions are capable of managing the corner case divisions presented in the previous problem, Integer.MIN_VALUE/-1
and Long.MIN_VALUE/-1
:
int x = Integer.MIN_VALUE; // or, x = Long.MIN_VALUE
Math.floorDiv(x, -1); // -2,147,483,648
Math.ceilDiv(x, -1); // -2,147...