168

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?

5
  • 6
    Wait, this is actually a duplicate question. It also has a perfect answer stackoverflow.com/a/4412200/1083704 – Val Jan 31 '13 at 13:41
  • 1
    @Val you mentioned modulo n equivalence classes: this range {0,1,2..n-1} is good for programmers, but {-n,n+1,n+2,-1} is equivalent and has the same right to exist – Timofey Jan 8 '14 at 20:44
  • 2
    No doubt part of the confusion stems from our colloquial name "mod" for this operator (leftover from the C family?), when the Java documentation actually calls it the "remainder" operator (docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html) – LarsH Dec 2 '16 at 15:21
  • 3
    K&R C defines the % operator as producing the remainder, but names it the modulus operator. Confusingly, en.wikipedia.org/wiki/Modulo_operation says that the modulo operation produces the remainder, both in computing and in mathematics... but also claims "The range of numbers for an integer modulo of n is 0 to n − 1."! – LarsH Dec 2 '16 at 15:45
  • There is no modulus operator in Java. % is a remainder operator. – user207421 Feb 19 '19 at 4:52
191

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)

16
  • 2
    @amit_gr - no I believe it works in general – andrewmu Mar 21 '11 at 23:56
  • 1
    you are right - my mistake. +1 – amit Mar 21 '11 at 23:59
  • 5
    @Cachapa please provide an example to support that statement. I believe the OP's solution is general already, consider that (((-3 % 4) + 4) % 4) = 1 (the intended result) and also that (((3 % 4) + 4) % 4) = 3 (also the intended result). It works with both positive and negative dividends. – The111 Jan 5 '13 at 8:54
  • 2
    @The111 Imagine the range of your integer is [-8, 7], (((5 % 6) + 6) % 6) = ((5 + 6) % 6) = (-5 % 6) = -5, but 5 % 6 is supposed to be positive. Substitute appropriately large numbers for 32 bit ints like 536887296 and 1610612736 and it is clear the second method is the better one. – Greg Rogers Jan 2 '14 at 20:23
  • 3
    @pgreze imagine the case where n=-1000 and m=3, the correct answer would be 2, but in your formula the answer is still negative. – Felipe Nardi Batista Sep 26 '18 at 11:17
129

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

0
2

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))
1
  • This expression didn't work for me. For negative values I was getting values between 1:m instead of the expected 0:m-1, as in the case where n is positive. The solution from andrewmu functioned as expected. – Cachapa Dec 16 '12 at 13:42
2
if b > 0:
    int mod = (mod = a % b) < 0 ? a + b : a;

Doesn't use the % operator twice.

5
  • How does the speed of this compare to the version with two % operators? – Christian Jan 8 '17 at 15:18
  • That's a good question. I perform a lot of premature optimization. I assume it saves a couple of CPU cycles. – Dico Jan 9 '17 at 17:26
  • 1
    @Dice : If you make a good case that this solution is better than the currently accepted solution, that would be valuable for people who browse this question. – Christian Jan 10 '17 at 13:27
  • 2
    Whether an if is faster than a % depends on your CPU and the data you feed it, due to branch prediction--ifs are faster if the condition has a predictable pattern. – Vitruvie Jun 23 '17 at 21:37
  • 2
    This is almost certainly slower because it has a branch, unless you know that the input will mostly be positive. If its random, then the branch prediction penalty will cost more clock cycles than an extra remainder calculation on most CPUs. Or, if you want to conditionally add a value based on whether an int is negative or not, try (maybeNegative >> 31) ^ thingToMaybeAdd + thingToAddTo – Scott Carey Sep 28 '18 at 17:26
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.