Fermat's little theorem

This page is about modular arithmetic. The integers modulo p define a field, denoted Fp.\

A finite field Fp is the set of integers {0,1,...,p-1}, and under both addition and multiplication there is an inverse element b for every element a in the set, such that a + b = 0 and a * b = 1.

Fermat's Little Theorem is a result in number theory that states that if **a ** is an integer and p is a prime number, then for all integers a:

apāˆ’1ā‰”1ā€Šmodā€Špa^{p-1} \equiv 1 \bmod p

This means that :

apāˆ’1āˆ’1p=0\frac{a^{p-1}-1}{p}=0

In cryptography, it is used in the modular exponentiation algorithm, which is a basic building block in many public key encryption algorithms such as the RSA algorithm.

Modular inversion

Modular inversion, also known as modular reciprocal, is the process of finding the multiplicative inverse of an integer a modulo p.

The multiplicative inverse of a modulo p is an integer b such that :

aāˆ—bā‰”1ā€Šmodā€Špa * b \equiv 1 \bmod p

b and is unique for each a and m couple

There is two methods in order to calculate the modular inverse of a number

Using extended Euclid's algorithm

The extended euclid's algorithm permit to quickly find the modular inverse such as :

aāˆ’1=uā€Šmodā€Špa^{-1} = u \bmod p

Where u is solution for :

aāˆ—u+pāˆ—v=1a*u+p*v = 1

This equation is solved using the extended Euclid's algorithm. Exemple with a = 3 and p = 13

a = 3, p = 13
gcd, u, v = egcd(a,p)
# 3 * -4 + 13 * 1 = 1
x = u % p
# 9 = -4 % 13
assert(a * x % p == 1 % p)

Continuing the Fermat's little theorem

The theorem says :

apāˆ’1ā‰”1ā€Šmodā€Špā€…ā€ŠāŸŗā€…ā€Šapāˆ’1ā€Šmodā€Šp=1a^{p-1} \equiv 1 \bmod p \iff a^{p-1} \bmod p = 1

The equation can be continued :

apāˆ’1ā‰”1ā€Šmodā€Špapāˆ’1āˆ—aāˆ’1ā‰”aāˆ’1ā€Šmodā€Špapāˆ’2āˆ—aāˆ—aāˆ’1ā‰”aāˆ’1ā€Šmodā€Špapāˆ’2ā‰”aāˆ’1ā€Šmodā€Špā€…ā€ŠāŸŗā€…ā€Šapāˆ’2ā€Šmodā€Šp=aāˆ’1a^{p-1} \equiv 1 \bmod p \\ a^{p-1} * a^{-1} \equiv a^{-1} \bmod p \\ a^{p-2} * a * a^{-1} \equiv a^{-1} \bmod p \\ a^{p-2} \equiv a^{-1} \bmod p \iff a^{p-2} \bmod p = a^{-1}

Using the same example as before :

# 3 * x ā‰” 1 mod 13
a = 3
p = 13
# x = a^(p-2) % p
# x = 3^(13-2) % 13
x = pow(a, p-2, p)
# x = 9
assert(a * x % p == 1 % p)

Resource

Last updated