[java] Mod in Java produces negative numbers

When I calculate int i = -1 % 2 I get -1 in Java. In Python, I get 1 as the result of -1 % 2. What do I have to do to get the same behavior in Java with the modulo function?

This question is related to java math mod

The answer is


If the modulus is a power of 2 then you can use a bitmask:

int i = -1 & ~-2; // -1 MOD 2 is 1

By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y is x - (x DIV y) * y where x DIV y is TRUNC(x / y)) and MOD requires a positive denominator and returns a positive result.


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 b > 0:
    int mod = (mod = a % b) < 0 ? a + b : a;

Doesn't use the % operator twice.


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))