Think grade-school long-division problems, before we learned about decimals. That’s a straight-forward way to think about it. The mod is just the remainder.
__0_r0 __0_r1 __0_r2 __0_r3 __0_r4
5 ) 0 5 ) 1 5 ) 2 5 ) 3 5 ) 4
__1_r0 __1_r1 __1_r2 __1_r3 __1_r4
5 ) 5 5 ) 6 5 ) 7 5 ) 8 5 ) 9
__2_r0 __2_r1 __2_r2 __2_r3 __2_r4
5 ) 10 5 ) 11 5 ) 12 5 ) 13 5 ) 14
__3_r0 __3_r1 __3_r2 __3_r3 __3_r4
5 ) 15 5 ) 16 5 ) 17 5 ) 18 5 ) 19
Since we are dividing by 5 here, the possible integer remainders will be the 5 values in the range 0-4 (or 0 to n-1). Mentally, you might think of mod as a sort of division where you use ‘%’ instead of ‘/’ and the result is the remainder rather than the quotient.
0 % 5 = 0 1 % 5 = 1 2 % 5 = 2 3 % 5 = 3 4 % 5 = 4
5 % 5 = 0 6 % 5 = 1 7 % 5 = 2 8 % 5 = 3 9 % 5 = 4
10 % 5 = 0 etc
If we think of the equation as x % n = r
, it has the useful property of assigning to r
the result of wrapping any value x
we give it into the range [0, n)
<-up to not inclu n
. This modular arithmetic is also called clock arithmetic because as you go around the clock adding numbers you reach a point at 12 where it loops. The hour hand on a clock is mod 12, though you’d prob want to interpret the 0 as a 12 in a clock app since that’s the convention (the second hand is mod 60, so values from 0 to 59).
Beyond just finding a remainder, it’s this looping or wrapping feature of mod that makes it most useful for programming. If you are dealing with rotations and want your values to stay in the range [0, 360), then you can use angle = angle % 360
to convert any rotation value to its corresponding angle within that range. Periodic functions like those from trig can be likewise constrained. Anytime you have a counter that you’d like to let grow and grow but would really like all the values to represent a position within a fixed range, you can use mod to do that. If you converted a 2D array, like an image, into a 1D array, you could still find the entry that corresponded to a given (x,y) coord by using mod (x = index % width
and y = math.floor(index / width)
).
Mod can work with decimals as the x
part (wouldn’t use decimals for n
even if it’s supported), so you could wrap values like 780.25 % 360 = 60.25 (degrees). Negative numbers can be used for things like wrapping circular buffers using positive or negative indices or wrapping negative screen or world coords if you need to use negative positions.
Applications for mod can be found from actual clock implementations to wrapping screen coords to hash functions, data validation, cryptography, and more, wherever data is worked with in a cyclical manner.