In C, the behaviour of the %
operation is defined as
a = (a/b)*b + (a%b)
Therefore,
(a%b) = a - (a/b)*b
That means
| a | b | a%b |
|-----+-----+-----|
| +ve | -ve | +ve |
| -ve | +ve | -ve |
| -ve | -ve | -ve |
| +ve | +ve | +ve |
ie, the sign of the value of the %
operator will be the sign of the first operand itself.
The %
operator in C is more like a remainder operator than modulo operator.
#include<stdio.h>
int main() {
"%d\n", 14%-8); // 6
printf("%d\n", -14%8); // -6
printf("%d\n", -14%-8); // -6
printf("%d\n", 14%8); // 6
printf(return 0;
}
The %
operator in Python is different from that in C. In Python, it is more like a proper modulo operator.
>>> 14%-8
-2
>>> -14%8
2
>>> -14%-8
-6
>>> 14%8
6
Further reading:
- https://en.wikipedia.org/wiki/Modulo_operation
- https://stackoverflow.com/questions/17524673/understanding-the-modulus-operator
- https://stackoverflow.com/questions/11720656/modulo-operation-with-negative-numbers
- https://stackoverflow.com/questions/13683563/whats-the-difference-between-mod-and-remainder
- http://web.archive.org/web/20121222204903/http://blogs.msdn.com/b/ericlippert/archive/2011/12/05/what-s-the-difference-remainder-vs-modulus.aspx