Learn / Maths for DSA

Modular inverse

Division under a prime modulus M means multiplying by an inverse: a⁻¹ with a × a⁻¹ ≡ 1 (mod M). By Fermat's little theorem a⁻¹ = a^(M-2) mod M, found with fast exponentiation in O(log M). The sheets this guide follows have no problems for this pattern.

How to recognise it

  • An answer 'modulo 10⁹ + 7' that involves a division.
  • nCr modulo a prime.
  • Probabilities or averages printed as P × Q⁻¹.

Fast power

power(a, e): r = 1
    while e > 0: if e odd: r = r × a mod M
                 a = a × a mod M; e = e / 2
    return r
inverse(a) = power(a, M - 2)

For a modulus that is not prime, use the extended Euclidean algorithm instead (it exists only when a and M are coprime).

Common mistakes

  • Overflow in a × a: use 64-bit values.
  • Using Fermat with a non-prime modulus.

Problems

No problems listed for this pattern yet.

Check yourself

Why can't you just divide remainders?

What does Fermat give for a prime M?

How fast is a^e mod M by squaring?