Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod in Java produces negative numbers [duplicate]

Tags:

java

math

mod

People also ask

What happens when you mod a negative number Java?

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.

Does mod work with negative numbers?

How does modulo work with negative numbers? When only the dividend is negative. When only the divisor is negative. When both the divisor and dividend are negative.

How do you mod a negative number?

Adding a thumb rule to all the answers above: negative number modulo k = k minus positive number modulo k. To find (−n)%k just find k−(n%k). Ex: (−144)%5=5−(144%5)=5−(4)=1.


The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. 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. There's some more information about it in this question.

You can find the positive value by doing this:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)


Since Java 8 you can use the Math.floorMod() method:

Math.floorMod(-1, 2); //== 1

Note: If the modulo-value (here 2) is negative, all output values will be negative too. :)

Source: https://stackoverflow.com/a/25830153/2311557


If you need n % m then:

int i = (n < 0) ? (m - (abs(n) % m) ) %m : (n % m);

mathematical explanation:

n = -1 * abs(n)
-> n % m = (-1 * abs(n) ) % m
-> (-1 * (abs(n) % m) ) % m
-> m - (abs(n) % m))

if b > 0:
    int mod = (mod = a % b) < 0 ? a + b : a;

Doesn't use the % operator twice.