C and Python – different behaviour of the modulo (%) operation

  1. Both variants are correct, however in mathematics (number theory in particular), Python’s modulo is most commonly used.
  2. 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).

Leave a Comment