Modular Inverse
Modular Inverse
Suppose we want to find the modular inverse x=a−1 of some element a modulo p, that is:
The inverse exists if and only if gcd(a,p)=1, i.e., when a is coprime with p.
When p is a prime number, the field Fp forms a finite field, and every nonzero element has an inverse. In that case, Fermat’s Little Theorem can be used to compute the inverse efficiently:
Note: This method only works when p is prime. For general modulus m (not necessarily prime), the modular inverse of a (if it exists) can be computed using the Extended Euclidean Algorithm.
Modular Inverse using Binary Extended Euclidean Algorithm
However, a more efficient method is to use the Extended Euclidean Algorithm, which solves the following equation:
Taking both sides modulo p yields:
Therefore, x is the modular inverse of a modulo p.
Core Idea
Let p be an odd prime, and let a and p be coprime. Starting with u=a and v=p, we apply the Binary GCD rules and reduce until either u or v becomes 1. The case where both u and v are even has already been handled in the previous stage and is thus excluded here.
Meanwhile, as in the Binary Extended Euclidean Algorithm, we initialize the variables as x1=1,y1=0,x2=0,y2=1, and maintain the following two invariants:
If we take both sides modulo p, we obtain simpler invariants:
At each step, we update the expressions while maintaining these invariants. Let’s examine just case 2 and case 4 as examples.
Case 2: u is even
If x1 is even, we update as:
If x1 is odd, we update as:
Case 4: u≥v and both u and v are odd
We update as:
Code
Here is the Python implementation of Algorithm 16: BEA for Inversion in 𝔽ₚ (Binary Extended Euclidean Algorithm for computing the modular inverse in a prime field) from here. Each step is annotated with comments to aid understanding.
For Montgomery Domain
A value a is transformed to its Montgomery representation as follows:
Therefore, if we naively compute the modular inverse of aR, we get:
However, the form we actually want is:
To achieve this, instead of initializing with b=1, we can set b=R2modp, and then return the result of the inversion algorithm.
Montgomery Inversion Algorithm
Another efficient algorithm for computing modular Inverse is Kaliski's Montgomery Inverse algorithm.
Kaliski’s Montgomery Inverse consists of two phases:
Almost Inverse phase
where n≤k≤2n
Correction phase
Core Idea
TODO(chokoble): Add reason why this code works.
Code
Here is the Python implementation of Algorithm 17: Montgomery Inversion in 𝔽ₚ from here.
Written by Ryan Kim of Fractalyze
Last updated