![]() |
VOOZH | about |
Given two integers n and m, find the modular multiplicative inverse of n under modulo m. The modular multiplicative inverse is an integer x such that:
n ⋅ x ≡ 1 (mod m)
Here dot means multiplication.
Examples:
Input: n = 3, m = 11
Output: 4
Explanation: (3 × 4) mod 11 = 1, so 4 is the modular inverse.
Note: 15 also works since (3 × 15) mod 11 = 1, but it is not in the range 1 to 10, so it is invalid.Input: n = 10, m = 17
Output: 12
Explanation: (10 × 12) mod 17 = 1, so 12 is the modular inverse of 10 under 17.
Table of Content
Try all values of x from 1 to m−1 and check each one. If (n ⋅ x) % m equals 1, then x is the modular inverse.
For n = 3 and m = 11:
Final answer = 4
4
Extended Euclidean algorithms takes two integers 'a' and 'b', then find their gcd, and also find 'x' and 'y' such that
ax + by = gcd(a, b)
To find the multiplicative inverse of 'n' under 'm', we put b = m in the above formula. Since we know that n and m are relatively prime, we can put the value of gcd as 1.
nx + my = 1
If we take modulo m on both sides, we get
nx + my ≡ 1 (mod m)
We can remove the second term on left side as 'my (mod m)' would always be 0 for an integer y.
nx ≡ 1 (mod m)
So the 'x' that
When n and m are coprime (gcd(n, m) = 1), the Extended Euclidean Algorithm finds values x and y such that n · x + m · y = 1. From this equation, x satisfies n · x ≡ 1 (mod m), so it is the modular multiplicative inverse of n.
The algorithm takes two integers a and b and finds x and y such that:
ax + by = gcd(a, b)For multiplicative inverse of n under m, we put b = m and a = n. Since we know that n and m are relatively prime, we can put the value of gcd as 1.
n⋅ x + m⋅ y = 1If we take modulo M on both sides, we get
n⋅ x + m⋅ y ≡ 1 (mod M)We can remove the second term on left side as 'm⋅ y (mod m)' would always be 0 for an integer y.
n⋅ x ≡ 1 (mod M)So the 'x' that we find using Extended Euclid Algorithm is the multiplicative inverse of 'n'
This approach can be implemented using both recursive and iterative versions of the Extended Euclidean Algorithm.
1. Recursive Implementation - O(log m) Time and O(log m) Space
4
2. Iterative Implementation - O(log m) Time and O(1) Space
4
When m is prime, we can use Fermat’s Little Theorem to compute the modular inverse efficiently. It allows us to replace division under modulo with exponentiation using fast power.
If we know m is prime, then we can use Fermat’s Little Theorem:
nm-1≡ 1 (mod m)
If we multiply both sides with n-1, we get
n-1≡ nm-2 (mod m)
4
Time Complexity:O(log m)
Auxiliary Space:O(log m), because of the internal recursion stack.