C and Python - different behaviour of the modulo (%) operation
I have found that the same mod operation produces different results depending on what language is being used.
In Python:
-1 % 10
produces 9
In C it produces -1 !
- Which one is the right modulo?
- How to make mod operation in C to be the same like in Python?
Solution 1:
- Both variants are correct, however in mathematics (number theory in particular), Python's modulo is most commonly used.
- In C, you do
((n % M) + M) % M
to get the same result as in Python. E. g.((-1 % 10) + 10) % 10
. Note, how it still works for positive integers:((17 % 10) + 10) % 10 == 17 % 10
, as well as for both variants of C implementations (positive or negative remainder).
Solution 2:
Python has a "true" modulo operation, while C has a remainder operation.
It has a direct relation with how the negative integer division is handled, i.e. rounded towards 0 or minus infinite. Python rounds towards minus infinite and C(99) towards 0, but in both languages (n/m)*m + n%m == n
, so the % operator must compensate in the correct direction.
Ada is more explicit and has both, as mod
and rem
.