VOOZH about

URL: https://www.geeksforgeeks.org/dsa/modular-multiplicative-inverse-1-n/

⇱ Modular multiplicative inverse from 1 to n - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Modular multiplicative inverse from 1 to n

Last Updated : 23 Nov, 2023

Give a positive integer n, find modular multiplicative inverse of all integer from 1 to n with respect to a big prime number, say, 'prime'.

The modular multiplicative inverse of a is an integer 'x' such that. 

 a x ? 1 (mod prime) 

Examples:

Input : n = 10, prime = 17
Output : 1 9 6 13 7 3 5 15 2 12
Explanation :
For 1, modular inverse is 1 as (1 * 1)%17 is 1
For 2, modular inverse is 9 as (2 * 9)%17 is 1
For 3, modular inverse is 6 as (3 * 6)%17 is 1
....... 

Input : n = 5, prime = 7
Output : 1 4 5 2 3

A simple solution is to one by one find modular inverse for every number. 

Output: 

1 9 6 13 7 3 5 15 2 12

Time Complexity: O(n*prime) 
Auxiliary Space: O(1)

An efficient solution is based on extended Euclid algorithm.

Extended Euclidean algorithm finds integer coefficients x and y such that: 

 ax + by = gcd(a, b)

Let us put b = prime, we get
 ax + prime * y = gcd(a, prime)

We know gcd(a, prime) = 1 because
one of the numbers is prime. So we
know
 ax + prime * y = 1 ---- (i)

Since prime * y is a multiple of prime,
x is modular multiplicative inverse of a.

 ax ? 1 (mod prime) 
 

We can recursively find x using below expression (see extended Euclid algorithm for details).

if we take for gcd(prime%a,prime) it'll be 1 

so (prime%a)*x1+prime*y1 = gcd(prime%a, prime)
=> (prime%a)*x1+prime*y1 = 1 -----(ii)
=>(prime - (prime/a)*a)x1 + prime*y1 = 1
=>-(prime/a)*x1*a+(x1+y1)*prime
using eq(i) and eq(ii) comparing the co-eeficient of a & prime we get

x = -(prime/a)*x1, & y = (x1+y1)

 x = inv(a) & x1 = inv(prime%a)

We use above relation to compute inverse using previously computed values.  

=> inverse(a) = -(prime/a)* inverse(prime % a) % prime
=> inverse(a) = (prime - (prime/a)) * inverse(prime % a) % prime

(-x % m = (m-x) % m)

We use Dynamic Programming approach that uses above recursive structure.

Dynamic Approach :

dp[1] = 1, 
dp[2] = dp[17%2]*(17-17/2)%17 = 9 
dp[3] = dp[17%3]*(17-17/3)%17 = 6
and so on..

Output:

1 9 6 13 7 3 5 15 2 12


Time Complexity: O(n) 
Auxiliary Space: O(n)

Comment