Modular Arithmetic

For any integer and any positive integer , known as the modulus, the division algorithm guarantees that there exist unique integers (the quotient) and (the remainder), such that

The remainder, written as , is the unique value in the set that is congruent to modulo .

In general, two integers are said to be congruent modulo , written , if they leave the same remainder when divided by . Equivalently, means that (i.e., the difference is divisible by ).

We now define arithmetic operations. Suppose and :

  1. Addition: .
  2. Multiplication: .
  3. Exponentiation: and . Note that modular arithmetic does not preserve congruence in the exponent.

Intuition & Proof

Floor division and the modulus are complementary operations: floor division gives the integer part of  divided by , while modulo gives the remainder . Any  can be decomposed into these parts using the equation . Here,  is the quotient, and  is the remainder. We now proceed with proving our arithmetic operations.

  • Addition. We know that and for some . Therefore, . By definition, and , so .
  • Multiplication. Just as above, we substitute for such that . This results in . Then, and , so .
  • Exponentiation. We already proved multiplication, so exponentiation is simply an extension of this.

Properties

(Canonical Representation) For any modulus , the set of all integers can be divided into exactly non-overlapping infinite sets, where each set contains all integers that leave the same remainder when divided by .

(Prime Modulus) For any prime modulus , all numbers in have a modular inverse.

This is trivially true, since for all .

(Wilson’s Theorem) It holds that if and only if is prime.

Note that . We now prove this theorem.

  • Sufficiency (): in the previous point, we observed that all numbers in have a modular inverse. Since all prime numbers are odd (for the exception of , which has a single element in the set of nonzero residues), this means that their set of residues are even, and therefore all elements can be matched with their inverse. Since the only two numbers that are their own inverses and cannot be matched are and , this means that
  • Necessity (): consider a composite number . Then there exist numbers for which , and therefore , which is equivalent to saying that As such,
    Therefore Wilson’s Theorem only holds if for all , which is only true for prime numbers.

(Fermat’s Little Theorem) For any prime modulus and any , it holds that .

Examples

Party Tricks

You are at a party celebrating your completion of the CS 70 midterm. Show off your modular arithmetic skills and impress your friends by quickly figuring out the last digit(s) of each of the following numbers: