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
  • 114,102
  • 10
  • 108
  • 170
ipkiss
  • 12,801
  • 29
  • 84
  • 119

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,017
  • 1
  • 6
  • 24