title | tags | |||
---|---|---|---|---|
07. Fermat's Little Theorem |
|
In the previous tutorial, we introduced addition, subtraction, multiplication, and division in modular arithmetic. In this tutorial, we will introduce modular exponentiation and Fermat's Little Theorem.
Modular exponentiation is the operation of exponentiation performed on a modulus and is widely used in cryptography:
where
For example, given
Modular exponentiation can also be written in congruence form:
Computing
According to modular arithmetic, we have:
If both
Therefore, we can multiply
Let's take
-
In the first step, we calculate
$7 * 7 \mod{13} =10$ . -
In the second step, we calculate
$10 * 7 \mod{13} = 5$ . -
In the third step, we calculate
$5 * 7 \mod{13} = 9$ . -
In the fourth step, we calculate
$9 * 7 \mod{13} = 11$ , and we are done. Therefore,$b = 11$ .
We can implement the optimized algorithm for modular exponentiation in Python as follows:
def mod_pow(base, exponent, modulus):
result = 1
# Expand the exponent into binary form and process each bit from high to low
while exponent > 0:
# If the current bit is 1, multiply by the current base and then take the modulus
if exponent % 2 == 1:
result = (result * base) % modulus
# Square the base and then take the modulus
base = (base * base) % modulus
# Right shift by one bit, equivalent to dividing by 2
exponent //= 2
return result
# Example: calculate (7^5) % 13
a = 7
c = 5
n = 13
result = mod_pow(a, c, n)
print(f"{a}^{c} mod {n} = {result}")
# 7^5 mod 13 = 11
Fermat's Little Theorem is an important theorem in number theory that provides a powerful tool for solving modular exponentiation problems.
Fermat's Little Theorem states that if
In other words,
Fermat's Little Theorem can also be written in another form. When
In other words,
First, we need to prove that the following equation holds for prime numbers
We expand the original equation using the binomial theorem. Except for
By induction, we can obtain:
If we expand
Therefore, the proof is complete.
Fermat's Little Theorem can also be used to calculate modular inverses. If
For example, when
Fermat's Little Theorem can be used for probabilistic primality testing. For a given prime number
In this tutorial, we introduced modular exponentiation and Fermat's Little Theorem. Fermat's Little Theorem is a very useful tool in number theory and cryptography, with a wide range of applications. By understanding Fermat's Little Theorem in depth, we can better apply it to solve mathematical problems related to primality testing, modular inverses, and more.