5.3 An intuitive understanding of the modulo operation

Once again, the operands are called dividend and divisor (hinting at how similar rem and mod are):

  1. modulus = dividend mod divisor

Consider the following example:

  1. x mod 3

This operation maps x into the range:

  1. [0,3) = {0,1,2}

That is, zero is included (opening square bracket), 3 is excluded (closing parenthesis).

How does mod perform this mapping? It is easy if x is already inside the range:

  1. > 0 mod 3
  2. 0
  3. > 2 mod 3
  4. 2

If x is greater than or equal to the upper boundary of the range, then the upper boundary is subtracted from x until it fits into the range:

  1. > 4 mod 3
  2. 1
  3. > 7 mod 3
  4. 1

That means we are getting the following mapping for non-negative integers:

  1. x: 0 1 2 3 4 5 6 7
  2. x mod 3: 0 1 2 0 1 2 0 1

This mapping is extended as follows, so that it includes negative integers:

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

Note how the range [0,3) is repeated over and over again.