In Kotlin I have seen that for function a.mod(n)
, if a
is negative the result is negative. Which is not what modulo is supposed to do. What can I do to have always positive modulo?
For example:
(-2).mod(9)
returns -2
and should be 7
.
These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results.
The modulus of a negative number is found by ignoring the minus sign. The modulus of a number is denoted by writing vertical lines around the number. Note also that the modulus of a negative number can be found by multiplying it by −1 since, for example, −(−8) = 8.
Is modulus always positive? The answer is “Yes”. Reason: The value of modulus of any number is always positive.
The sign of the first operand decides the sign of the result. x % y always equals x % -y .
The best answer is Math.floorMod()
as Paul Lammertsma mentioned in a comment, since it is the most mathematically correct: It always returns a value between zero (inclusive) and the divisor (exclusive), and does so regardless of whether either or both arguments are negative.
It's even invariant across flipping the signs of all the inputs and output:
Math.floorMod(11, 9) => 2
Math.floorMod(-11, -9) => -2
Math.floorMod(-11, 9) => 7
Math.floorMod(11, -9) => -7
Math.floorMod
is available since JDK 1.8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With