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?

- 25,249
- 40
- 134
- 225
-
6Wait, this is actually a duplicate question. It also has a perfect answer http://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 08 '14 at 20:44
-
2No 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 (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html) – LarsH Dec 02 '16 at 15:21
-
3K&R C defines the `%` operator as producing the **remainder**, but names it the **modulus** operator. Confusingly, https://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 02 '16 at 15:45
-
There is no modulus operator in Java. % is a remainder operator. – user207421 Feb 19 '19 at 04:52
5 Answers
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)
-
-
2
-
1
-
I'd just like to make clear that this only works for negative dividends. A general solution will require a conditional expression: (a < 0) ? ((a % b) + b) % b : (a % b) – Cachapa Dec 16 '12 at 13:37
-
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 05 '13 at 08: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 02 '14 at 20:23
-
@Greg Rogers fair enough. I hadn't considered overflow (nor had it been mentioned prior to your post). Thanks for the insight! – The111 Jan 03 '14 at 01:29
-
1
-
I don't know why everyone up-voted this, but it is wrong in JDK8 at least. example -5 % 3 gives -2, not -1, so the "if (i<0) i += m" trick is not relevant. We should be doing abs(result) to get the correct answer – javaPhobic May 05 '17 at 05:56
-
1actually ignore my comment above, I didn't realize the OP was trying to replicate python, I thought he/she just wanted the positive equivalent – javaPhobic May 05 '17 at 06:04
-
-
4@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
-
1faster, as shifting, masking, and adding are significantly faster than a second % op (and even moreso vs the conditional branch): `int remainder = (x % n); return (remainder >> 31) & n + n;` – Scott Carey Oct 01 '18 at 18:50
-
-
I'm confused regarding the second `%`. Why not just `((n % m) + m)`? This should also give the positive modulo no? – csstudent1418 Dec 16 '20 at 20:14
-
@csstudent1418 That will break in case where `n` is positive, returning a result `> m` – Matthew Jensen Jul 26 '21 at 21:17
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. :)
if b > 0:
int mod = (mod = a % b) < 0 ? a + b : a;
Doesn't use the %
operator twice.
-
How does the speed of this compare to the version with two % operators? – Christian Jan 08 '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 09 '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
-
2Whether an `if` is faster than a `%` depends on your CPU and the data you feed it, due to branch prediction--`if`s are faster if the condition has a predictable pattern. – Vitruvie Jun 23 '17 at 21:37
-
2This 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
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))

- 175,853
- 27
- 231
- 333
-
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
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.

- 54,642
- 8
- 60
- 72