5

I have couple line of C code testing the modulo operator as follows:

// line 1
printf("%d\n", 5 % (-3)); => output: 2
// line 2
printf("%d\n", -5 % 3); => output: -2

I know that the sign of the modulo depends on the sign of the numerator, but I am curious why not otherwise?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
ipkiss
  • 13,311
  • 33
  • 88
  • 123

1 Answers1

3
5/(-3) = -1;
(-5)/3 = -1; 

If that is agreed then let's calculate the remainder

Remainder = Dividend - ( Divisor * Factor)

5 - (-3 * -1) = 2
-5 - (3 * -1) = -2 
Pushparaj
  • 1,039
  • 1
  • 6
  • 26