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
3 mod 5 = 3because 3 divided by 5 is 0 with remainder 3.m mod n = nwherem < n5 mod 3 = 2because 5 divided by 3 is 1 with remainder 2.0 <= m mod n <= nwherem > n
From 1.
0 mod 3 = 01 mod 3 = 12 mod 3 = 2
From 2.
3 mod 3 = 04 mod 3 = 15 mod 3 = 26 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)
-5 mod 3 = 1because -5 divided by 3 is -1 with remainder 2. Fitting this to the equationdividend = divisor*quotient + remainder,5 = 3(-1) + 2Nani! 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?-6Divide 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
- 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
| Expression | Python Result | Java Result |
|---|---|---|
| 5 % 3 | 2 | 2 |
| 5 % -3 | -1 | 2 |
| -5 % 3 | 1 | -2 |
| -5 % -3 | -2 | -2 |