mulDiv
a · b / divisor, rounded as rounding says, or null when the rounded result does not fit in a Long.
The product is formed in 128 bits, so it never overflows on the way: only the final quotient has to fit. That is the difference from a.timesOrNull(b)?.let { it / divisor }, which refuses (2⁶² · 4) / 8 although the answer, 2⁶¹, is small.
Throws
if divisor is zero, as Long / 0 does.
Samples
val big = 1L shl 62
// big · 4 overflows a Long, but big · 4 / 8 = 2⁶¹ does not, and mulDiv only needs the answer to fit.
assertEquals(1L shl 61, mulDiv(big, 4L, 8L, Rounding.FLOOR))
assertEquals(3L, mulDiv(7L, 1L, 2L, Rounding.FLOOR))
assertEquals(4L, mulDiv(7L, 1L, 2L, Rounding.CEILING))
assertNull(mulDiv(Long.MAX_VALUE, 2L, 1L, Rounding.FLOOR))Content copied to clipboard
a · b / divisor for a 128-bit a, rounded as rounding says, or null when the rounded result does not fit in an Int128.
The product is formed in 192 bits, so, as with the Long form, only the final quotient has to fit. It is the shape a position takes when a wide count is read on a fractional scale, a · n / d with a itself past Long.
Throws
if divisor is zero, as Long / 0 does.
Samples
val big = Int128.fromTwosComplement(1L shl 62, 0L) // 2¹²⁶
// 2¹²⁶ · 4 is past 128 bits, but 2¹²⁶ · 4 / 8 = 2¹²⁵ is not.
assertEquals(Int128.fromTwosComplement(1L shl 61, 0L), mulDiv(big, 4L, 8L, Rounding.FLOOR))
assertEquals(Int128.of(26L), mulDiv(Int128.of(5L), 16L, 3L, Rounding.FLOOR))
assertNull(mulDiv(big, 4L, 1L, Rounding.FLOOR))Content copied to clipboard