Skip to main content

Modular Arithmetic

It's a type of arithmetic that deals with remainders. The numbers wrap around after they reach a certain value. The remainder is the mod value of that number.

It's also called clock arithmetic, since the numbers go in a circle. In N modulo, you have only 0 to N-1.

modulo vs division

Modulo returns the remainder. Division returns the quotient.

For example, to pull digits out of a large number, you use modulo 10 and division by 10.

modular-arithmetic
Mental model for modular operations

The math way to show modular is by dividing. The right mental model, though, is a counter on a circle. Mod is what remains on the circle in the last round.

Clock is mod 12

When we say a clock is mod 12, only 0 to 11 are allowed. For practical reasons, clocks show 1 to 12. The idea is still the same.

4 hours after 9 AM is 13, which we call 1 PM.

Binary Overflow

Modular arithmetic also shows up in binary overflow. In binary arithmetic, the overflow bit's just dropped. This brings the value back to the start of the circle. See binary arithmetic article for more details.

Setting zeros makes module of different systems

Take an N bit wide value. Setting the MSB gives the modulo value for an N-1 bit width. This is why an AND with a set of low bits set to 1 gives the modulo directly. You skip the costly modulo operation.

This works only when the AND uses all ones.

Circular data structures

Circular queues and circular linked lists use this too. They use modular arithmetic to wrap the indices around.

On a next operation, if the value is already at the end, you wrap to the start with modulo. It then points to the start of the queue or list again.