Why modulo operator is not working as intended in C and Java?
Asked
Active
Viewed 1,153 times
4
-
7Remainder vs modulus – tckmn Mar 22 '13 at 18:14
-
1I much prefer the remainder version, but in java the design decision was made differently :-( – MrSmith42 Mar 22 '13 at 18:38
-
Because negative % something is implementation defined? – vonbrand Mar 22 '13 at 21:39
4 Answers
3
Python's %-operator calculates the mathematical remainder, not the modulus. The remainder is by definition a number between 0 and the divisor, it doesn't depend on the sign of the dividend like the modulus.

Joni
- 108,737
- 14
- 143
- 193
-
Actually, you've got it backward. If y is positive, then "x mod y" will be between 0 and y-1, while the sign of "x remainder y" will depend upon that of x. I can't think of any occasions where I've ever used the "%" operator on a negative number and wanted the remainder, but for a long time the standard only mandated particular behavior for "%" with positive operands; in those cases "mod" and "remainder" were synonymous, and "mod" was easier to say, so that's the name that stuck. – supercat Sep 26 '14 at 19:05
1
It is working as specified.
The contract is that
a == (a/b) * b + (a % b)
and integer division truncates toward zero. So with a negative dividend, you get a negative remainder.

Daniel Fischer
- 181,706
- 17
- 308
- 431
0
Not sure about python but %
operator in java returns the remainder obtained after the division.
-1%26
breaking it down:
26)-1(0
0
---
-1 ---> Remainder as (-1+0=-1)

PermGenError
- 45,977
- 8
- 87
- 106