Modular arithmetic

Modular arithmetic: x mod n is the remainder when x is divided by n:

      7 = 1 mod 6
      33 = 3 mod 5
      33 = 3 mod 6
      51 = 0 mod 17

Modular addition:

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

The additive inverse of 2 mod 6 is denoted -2 mod 6 and it is the number that must be added to 2 mod 6 to get 0. So

      -2 mod 6 = 4.

Modular multiplication:

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

The multiplicative inverse of 5 mod 6 is denoted 5-1 mod 6 and it is the number that must be multiplied by 5 mod 6 to get 1. So

      5-1 mod 6 = 5.

What is 2-1 mod 6?

Note that

      (a + b)(mod n) = (a (mod n) + b (mod n)) (mod n)

and

      (a b)(mod n) = ((a (mod n)) (b (mod n))) (mod n)

Two number x and y are relatively prime if they have no common factors other than 1. The multiplicative inverse x-1 mod y exists only when x and y are relatively prime. Since 2 and 6 have a common factor of 2, 2-1 mod 6 does not exist. The multiplicative inverse can be found (if it exists) using the Euclidean Algorithm.

The totient function, φ(n), is the number of numbers less than n that are relatively prime to n. For example

      φ(4) = 2
      φ(5) = 4
      φ(12) = 4
      φ(p) = p - 1 if p is prime
      φ(pq) = (p-1)(q-1) if p and q are prime

For RSA, we must perform modular exponentiation of large numbers. How can we do this efficiently? Consider 520 mod 35. The obvious way to compute this is

      520 = 95367431640625 = 25 mod 35

But this will be problematic for large numbers.

Instead, we can note that 20 is 10100 in binary and compute the exponentiation from the sequence of powers (in binary) 1, 10, 101, 1010, 10100 as

      51 = 5 mod 35
      52 = (51)2 = 52 = 25 mod 35
      55 = (52)2 ⋅ 5 = 252 ⋅ 5 = 3125 = 10 mod 35
      510 = (55)2 = 102 = 100 = 30 mod 35
      520 = (510)2 = 302 = 900 = 25 mod 35

This method is known as repeated squaring.