Modular Inverse
Presentation: https://youtu.be/eEU1v1ZPHe0
Last updated
Presentation: https://youtu.be/eEU1v1ZPHe0
Last updated
Suppose we want to find the modular inverse of some element modulo , that is:
The inverse exists if and only if , i.e., when is coprime with .
When is a prime number, the field forms a finite field, and every nonzero element has an inverse. In that case, can be used to compute the inverse efficiently:
Note: This method only works when is prime. For general modulus (not necessarily prime), the modular inverse of (if it exists) can be computed using the Extended Euclidean Algorithm.
However, a more efficient method is to use the , which solves the following equation:
At each step, we update the expressions while maintaining these invariants. Let’s examine just case 2 and case 4 as examples.
We update as:
However, the form we actually want is:
Another efficient algorithm for computing modular Inverse is Kaliski's Montgomery Inverse algorithm.
Kaliski’s Montgomery Inverse consists of two phases:
Almost Inverse phase
Correction phase
TODO(chokoble): Add reason why this code works.
Taking both sides modulo yields:
Therefore, is the modular inverse of modulo .
Let be an odd prime, and let and be coprime. Starting with and , we apply the Binary GCD rules and reduce until either or becomes 1. The case where both and 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 , and maintain the following two invariants:
If we take both sides modulo , we obtain simpler invariants:
If is even, we update as:
If is odd, we update as:
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 . Each step is annotated with comments to aid understanding.
A value is transformed to its as follows:
Therefore, if we naively compute the modular inverse of , we get:
To achieve this, instead of initializing with , we can set , and then return the result of the inversion algorithm.
where
Here is the Python implementation of Algorithm 17: Montgomery Inversion in 𝔽ₚ from .
Written by from