Skip to main content

Modulus

Modulo is the clock that wraps around after n in m % n. 5 mod 3 = 2 because we need to take 2 more steps after completing a full rotation 3 mod 5 = 3 because there was no wrap around.

For positive number(m & n) it is the remainder

  1. 3 mod 5 = 3 because 3 divided by 5 is 0 with remainder 3. m mod n = n where m < n
  2. 5 mod 3 = 2 because 5 divided by 3 is 1 with remainder 2. 0 <= m mod n <= n where m > n

From 1.

  • 0 mod 3 = 0
  • 1 mod 3 = 1
  • 2 mod 3 = 2

From 2.

  • 3 mod 3 = 0
  • 4 mod 3 = 1
  • 5 mod 3 = 2
  • 6 mod 3 = 0

[!IMPORTANT] Modulo is not just the remainder of a division, instead it is something that satisfied the equation:

a = n·q + r        (for some integer q)
0 ≤ r < |n| (if n > 0)
  1. -5 mod 3 = 1 because -5 divided by 3 is -1 with remainder 2. Fitting this to the equation dividend = divisor*quotient + remainder, 5 = 3(-1) + 2 Nani! this is -1 and not 5. Remainder are positive number left behind after division. What's the multiple of 3 closest to -5 but lower than -5? -6 Divide it by 3 and you get quotient (-2) leaving the remainder 1. The wrap around concept still applies, imagine the clock with 3 hours, we're just wrapping around in anti-clockwise direction.

Python -5 % 3 = 1 modulo Java -5 % 3 = -2 remainder

  1. Negative modulo:

5 mod -3: This clock is different , hours are -2, -1, 0 instead of 1, 2, 0. The state space is different. So moving forward by 5 steps means, -2, -1, 0, -2, -1 hence 5 mod -3 = -1

-5 mod -3: Moving 5 steps backward means: -1, -2, 0, -1, -2 hence -5 mod -3 = -2

ExpressionPython ResultJava Result
5 % 322
5 % -3-12
-5 % 31-2
-5 % -3-2-2