Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin negative modulo returns negative value

Tags:

modulo

kotlin

mod

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.

like image 423
Damia Fuentes Avatar asked Nov 23 '17 11:11

Damia Fuentes


People also ask

Does modulo return negative?

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.

How do you solve a negative modulo?

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 Result of modulo always positive?

Is modulus always positive? The answer is “Yes”. Reason: The value of modulus of any number is always positive.

What does the Java modulo operator return when given a negative number?

The sign of the first operand decides the sign of the result. x % y always equals x % -y .


1 Answers

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.

like image 73
treat your mods well Avatar answered Sep 17 '22 21:09

treat your mods well