5.2 An intuitive understanding of the remainder operation

The operands of the remainder operator are called dividend and divisor:

  1. remainder = dividend rem divisor

How is the result computed? Consider the following expression:

  1. 7 rem 3

We remove 3 from the dividend until we are left with a value that is smaller than 3:

  1. 7 rem 3 = 4 rem 3 = 1 rem 3 = 1

What do we do if the dividend is negative?

  1. -7 rem 3

This time, we add 3 to the dividend until we have a value that is smaller than -3:

  1. -7 rem 3 = -4 rem 3 = -1 rem 3 = -1

It is insightful to map out the results for a fixed divisor:

  1. x: -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
  2. x rem 3: -1 0 -2 -1 0 -2 -1 0 1 2 0 1 2 0 1

Among the results, we can see a symmetry: x and -x produce the same results, but with opposite signs.