Modulo operation with negative numbers

Alva picture Alva · Jul 30, 2012 · Viewed 231.9k times · Source

In a C program i was trying the below operations(Just to check the behavior )

 x = 5 % (-3);
 y = (-5) % (3);
 z = (-5) % (-3); 

printf("%d ,%d ,%d", x, y, z); 

gave me output as (2, -2 , -2) in gcc . I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?

Answer

ArjunShankar picture ArjunShankar · Jul 30, 2012

C99 requires that when a/b is representable:

(a/b) * b + a%b shall equal a

This makes sense, logically. Right?

Let's see what this leads to:


Example A. 5/(-3) is -1

=> (-1) * (-3) + 5%(-3) = 5

This can only happen if 5%(-3) is 2.


Example B. (-5)/3 is -1

=> (-1) * 3 + (-5)%3 = -5

This can only happen if (-5)%3 is -2