Modulo operation with negative numbers

Tags: / c / python /

About modulo operation involving negative numbers being a bit.

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() {
    printf("%d\n", 14%-8);   //  6
    printf("%d\n", -14%8);   // -6
    printf("%d\n", -14%-8);  // -6
    printf("%d\n", 14%8);    //  6
    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: