0

I understand that modulo follows the formula "Quotient × Divisor + Remainder = Dividend," but what I do not understand is how $4 \mod{-5}$ fits as $-1 \times -5 + (-1) = 4$ in the equation. Why isn't it $0 \times (-5) + 4 = 4$, giving us a remainder of $4$ like it does when we do $4 \mod{5}$ in $0 \times 5 + 4 = 4$. What changes when we negate the divisor? How does this make sense?

If the number was greater than five, such as $6$, then negating the $-5$ with a $-1$ like the formula does would make sense, because then you could treat the whole thing as if everything was positive. However I don't understand why $4 \mod (-5)$ is treated the same, why not make the Quotient "$-0$" instead?

Bill Dubuque
  • 272,048

1 Answers1

1

Computer languages with integer division generally support a pair of operators:

  • a DIV b (spelled // in Python 2.2+) is the quotient a/b converted to an integer.
  • a MOD b (often spelled %) is the remainder of the division.

For the sake of consistency, MOD must be defined as:

$$a \operatorname{mod} b := a - (a \operatorname{div} b) \cdot b$$

When $a$ and $b$ are both positive, everybody generally agrees that $a \operatorname{div} b = \lfloor \frac{a}{b} \rfloor$. The confusion comes when negative numbers are involved.

  • In C, 4 / -5 is truncated towards zero. So 4 % -5 $= 4 - (0)(-5) = 4$.
  • In Python, 4 // -5 is floored to $-1$. So 4 % -5 $= 4 - (-1)(-5) = -1$.
Dan
  • 14,978