Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Multiplicative order
Next article icon

Modular multiplicative inverse

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers A and M, find the modular multiplicative inverse of A under modulo M.
The modular multiplicative inverse is an integer X such that:

A X ≡ 1 (mod M)   

Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*0 mod M will never be 1). The multiplicative inverse of "A modulo M" exists if and only if A and M are relatively prime (i.e. if gcd(A, M) = 1)

Examples: 

Input: A = 3, M = 11
Output: 4
Explanation: Since (4*3) mod 11 = 1, 4 is modulo inverse of 3(under 11).
One might think, 15 also as a valid output as "(15*3) mod 11" 
is also 1, but 15 is not in range {1, 2, ... 10}, so not valid.

Input:  A = 10, M = 17
Output: 12
Explamation: Since (10*12) mod 17 = 1, 12 is modulo inverse of 10(under 17).

Naive Approach:  To solve the problem, follow the below idea:

A naive method is to try all numbers from 1 to m. For every number x, check if (A * X) % M is 1

Below is the implementation of the above approach:

C++
// C++ program to find modular // inverse of A under modulo M #include <bits/stdc++.h> using namespace std;  // A naive method to find modular // multiplicative inverse of 'A' // under modulo 'M'  int modInverse(int A, int M) {     for (int X = 1; X < M; X++)         if (((A % M) * (X % M)) % M == 1)             return X; }  // Driver code int main() {     int A = 3, M = 11;      // Function call     cout << modInverse(A, M);     return 0; } 
Java
// Java program to find modular inverse // of A under modulo M import java.io.*;  class GFG {      // A naive method to find modulor     // multiplicative inverse of A     // under modulo M     static int modInverse(int A, int M)     {          for (int X = 1; X < M; X++)             if (((A % M) * (X % M)) % M == 1)                 return X;         return 1;     }      // Driver Code     public static void main(String args[])     {         int A = 3, M = 11;          // Function call         System.out.println(modInverse(A, M));     } }  /*This code is contributed by Nikita Tiwari.*/ 
Python
# Python3 program to find modular # inverse of A under modulo M  # A naive method to find modulor # multiplicative inverse of A # under modulo M   def modInverse(A, M):      for X in range(1, M):         if (((A % M) * (X % M)) % M == 1):             return X     return -1   # Driver Code if __name__ == "__main__":     A = 3     M = 11      # Function call     print(modInverse(A, M))  # This code is contributed by Nikita Tiwari. 
C#
// C# program to find modular inverse // of A under modulo M using System;  class GFG {      // A naive method to find modulor     // multiplicative inverse of A     // under modulo M     static int modInverse(int A, int M)     {          for (int X = 1; X < M; X++)             if (((A % M) * (X % M)) % M == 1)                 return X;         return 1;     }      // Driver Code     public static void Main()     {         int A = 3, M = 11;          // Function call         Console.WriteLine(modInverse(A, M));     } }  // This code is contributed by anuj_67. 
JavaScript
<script>  // Javascript program to find modular  // inverse of a under modulo m  // A naive method to find modulor // multiplicative inverse of // 'a' under modulo 'm' function modInverse(a, m) {     for(let x = 1; x < m; x++)         if (((a % m) * (x % m)) % m == 1)             return x; }  // Driver Code let a = 3;  let m = 11;  // Function call document.write(modInverse(a, m));  // This code is contributed by _saurabh_jaiswal.  </script> 
PHP
<?php // PHP program to find modular  // inverse of A under modulo M  // A naive method to find modulor // multiplicative inverse of // A under modulo M function modInverse( $A, $M) {          for ($X = 1; $X < $M; $X++)         if ((($A%$M) * ($X%$M)) % $M == 1)             return $X; }  // Driver Code $A = 3;  $M = 11;  // Function call echo modInverse($A, $M);  // This code is contributed by anuj_67. ?> 

Output
4 

Time Complexity: O(M)
Auxiliary Space: O(1)

Modular multiplicative inverse when M and A are coprime or gcd(A, M)=1:

The idea is to use Extended Euclidean algorithms that take 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 'A' under 'M', we put b = M in the above formula. Since we know that A and M are relatively prime, we can put the value of gcd as 1.

Ax + My = 1

If we take modulo M on both sides, we get

Ax + 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. 

Ax  ≡ 1 (mod M)

So the 'x' that we can find using Extended Euclid Algorithm is the multiplicative inverse of 'A'

Below is the implementation of the above approach:  

C++
// C++ program to find multiplicative modulo // inverse using Extended Euclid algorithm. #include <bits/stdc++.h> using namespace std;  // Function for extended Euclidean Algorithm int gcdExtended(int a, int b, int* x, int* y);  // Function to find modulo inverse of a void modInverse(int A, int M) {     int x, y;     int g = gcdExtended(A, M, &x, &y);     if (g != 1)         cout << "Inverse doesn't exist";     else {          // m is added to handle negative x         int res = (x % M + M) % M;         cout << "Modular multiplicative inverse is " << res;     } }  // Function for extended Euclidean Algorithm int gcdExtended(int a, int b, int* x, int* y) {      // Base Case     if (a == 0) {         *x = 0, *y = 1;         return b;     }      // To store results of recursive call     int x1, y1;     int gcd = gcdExtended(b % a, a, &x1, &y1);      // Update x and y using results of recursive     // call     *x = y1 - (b / a) * x1;     *y = x1;      return gcd; }  // Driver Code int main() {     int A = 3, M = 11;      // Function call     modInverse(A, M);     return 0; }  // This code is contributed by khushboogoyal499 
C
// C program to find multiplicative modulo inverse using // Extended Euclid algorithm. #include <stdio.h>  // C function for extended Euclidean Algorithm int gcdExtended(int a, int b, int* x, int* y);  // Function to find modulo inverse of a void modInverse(int A, int M) {     int x, y;     int g = gcdExtended(A, M, &x, &y);     if (g != 1)         printf("Inverse doesn't exist");     else {         // m is added to handle negative x         int res = (x % M + M) % M;         printf("Modular multiplicative inverse is %d", res);     } }  // C function for extended Euclidean Algorithm int gcdExtended(int a, int b, int* x, int* y) {     // Base Case     if (a == 0) {         *x = 0, *y = 1;         return b;     }      int x1, y1; // To store results of recursive call     int gcd = gcdExtended(b % a, a, &x1, &y1);      // Update x and y using results of recursive     // call     *x = y1 - (b / a) * x1;     *y = x1;      return gcd; }  // Driver Code int main() {     int A = 3, M = 11;      // Function call     modInverse(A, M);     return 0; } 
Java
// java program to find multiplicative modulo // inverse using Extended Euclid algorithm. public class GFG {      // Global Variables     public static int x;     public static int y;      // Function for extended Euclidean Algorithm     static int gcdExtended(int a, int b)     {          // Base Case         if (a == 0) {             x = 0;             y = 1;             return b;         }          // To store results of recursive call         int gcd = gcdExtended(b % a, a);         int x1 = x;         int y1 = y;          // Update x and y using results of recursive         // call         int tmp = b / a;         x = y1 - tmp * x1;         y = x1;          return gcd;     }      static void modInverse(int A, int M)     {         int g = gcdExtended(A, M);         if (g != 1) {             System.out.println("Inverse doesn't exist");         }         else {              // m is added to handle negative x             int res = (x % M + M) % M;             System.out.println(                 "Modular multiplicative inverse is " + res);         }     }      // Driver code     public static void main(String[] args)     {         int A = 3, M = 11;          // Function Call         modInverse(A, M);     } }  // The code is contributed by Gautam goel (gautamgoel962) 
Python
# Python3 program to find multiplicative modulo # inverse using Extended Euclid algorithm.  # Global Variables x, y = 0, 1  # Function for extended Euclidean Algorithm   def gcdExtended(a, b):     global x, y      # Base Case     if (a == 0):         x = 0         y = 1         return b      # To store results of recursive call     gcd = gcdExtended(b % a, a)     x1 = x     y1 = y      # Update x and y using results of recursive     # call     x = y1 - (b // a) * x1     y = x1      return gcd   def modInverse(A, M):      g = gcdExtended(A, M)     if (g != 1):         print("Inverse doesn't exist")      else:          # m is added to handle negative x         res = (x % M + M) % M         print("Modular multiplicative inverse is ", res)   # Driver Code if __name__ == "__main__":     A = 3     M = 11      # Function call     modInverse(A, M)   # This code is contributed by phasing17 
C#
// C# program to find multiplicative modulo // inverse using Extended Euclid algorithm.  using System;  public class GFG {     public static int x, y;      // Function for extended Euclidean Algorithm     static int gcdExtended(int a, int b)     {          // Base Case         if (a == 0) {             x = 0;             y = 1;             return b;         }          // To store results of recursive call         int gcd = gcdExtended(b % a, a);         int x1 = x;         int y1 = y;          // Update x and y using results of recursive         // call         x = y1 - (b / a) * x1;         y = x1;          return gcd;     }      // Function to find modulo inverse of a     static void modInverse(int A, int M)     {         int g = gcdExtended(A, M);         if (g != 1)             Console.Write("Inverse doesn't exist");         else {              // M is added to handle negative x             int res = (x % M + M) % M;             Console.Write(                 "Modular multiplicative inverse is " + res);         }     }      // Driver Code     public static void Main(string[] args)     {         int A = 3, M = 11;          // Function call         modInverse(A, M);     } }  // this code is contributed by phasing17 
JavaScript
<script> // JavaScript program to find multiplicative modulo // inverse using Extended Euclid algorithm.  // Global Variables let x, y;  // Function for extended Euclidean Algorithm function gcdExtended(a, b){           // Base Case     if (a == 0)     {         x = 0;         y = 1;         return b;     }           // To store results of recursive call         let gcd = gcdExtended(b % a, a);     let x1 = x;     let y1 = y;      // Update x and y using results of recursive     // call     x = y1 - Math.floor(b / a) * x1;     y = x1;       return gcd; }  function modInverse(a, m) {     let g = gcdExtended(a, m);     if (g != 1){         document.write("Inverse doesn't exist");     }     else{                   // m is added to handle negative x         let res = (x % m + m) % m;         document.write("Modular multiplicative inverse is ", res);         } }  // Driver Code {     let a = 3, m = 11;         // Function call     modInverse(a, m); }   // This code is contributed by Gautam goel (gautamgoel962) </script> 
PHP
<?php // PHP program to find multiplicative modulo  // inverse using Extended Euclid algorithm. // Function to find modulo inverse of a function modInverse($A, $M) {     $x = 0;     $y = 0;     $g = gcdExtended($A, $M, $x, $y);     if ($g != 1)         echo "Inverse doesn't exist";     else     {         // m is added to handle negative x         $res = ($x % $M + $M) % $M;         echo "Modular multiplicative " .                     "inverse is " . $res;     } }  // function for extended Euclidean Algorithm function gcdExtended($a, $b, &$x, &$y) {     // Base Case     if ($a == 0)     {         $x = 0;         $y = 1;         return $b;     }      $x1;     $y1; // To store results of recursive call     $gcd = gcdExtended($b%$a, $a, $x1, $y1);      // Update x and y using results of      // recursive call     $x = $y1 - (int)($b/$a) * $x1;     $y = $x1;      return $gcd; }  // Driver Code $A = 3; $M = 11;  // Function call modInverse($A, $M);  // This code is contributed by chandan_jnu ?> 

Output
Modular multiplicative inverse is 4 

Time Complexity: O(log M)
Auxiliary Space: O(log M), because of the internal recursion stack.


 Iterative Implementation of the above approach:

C++
// Iterative C++ program to find modular // inverse using extended Euclid algorithm  #include <bits/stdc++.h> using namespace std;  // Returns modulo inverse of a with respect // to m using extended Euclid Algorithm // Assumption: a and m are coprimes, i.e., // gcd(A, M) = 1 int modInverse(int A, int M) {     int m0 = M;     int y = 0, x = 1;      if (M == 1)         return 0;      while (A > 1) {         // q is quotient         int q = A / M;         int t = M;          // m is remainder now, process same as         // Euclid's algo         M = A % M, A = t;         t = y;          // Update y and x         y = x - q * y;         x = t;     }      // Make x positive     if (x < 0)         x += m0;      return x; }  // Driver Code int main() {     int A = 3, M = 11;      // Function call     cout << "Modular multiplicative inverse is "          << modInverse(A, M);     return 0; } // this code is contributed by shivanisinghss2110 
C
// Iterative C program to find modular // inverse using extended Euclid algorithm  #include <stdio.h>  // Returns modulo inverse of a with respect // to m using extended Euclid Algorithm // Assumption: a and m are coprimes, i.e., // gcd(A, M) = 1 int modInverse(int A, int M) {     int m0 = M;     int y = 0, x = 1;      if (M == 1)         return 0;      while (A > 1) {         // q is quotient         int q = A / M;         int t = M;          // m is remainder now, process same as         // Euclid's algo         M = A % M, A = t;         t = y;          // Update y and x         y = x - q * y;         x = t;     }      // Make x positive     if (x < 0)         x += m0;      return x; }  // Driver Code int main() {     int A = 3, M = 11;      // Function call     printf("Modular multiplicative inverse is %d\n",            modInverse(A, M));     return 0; } 
Java
// Iterative Java program to find modular // inverse using extended Euclid algorithm  class GFG {      // Returns modulo inverse of a with     // respect to m using extended Euclid     // Algorithm Assumption: a and m are     // coprimes, i.e., gcd(A, M) = 1     static int modInverse(int A, int M)     {         int m0 = M;         int y = 0, x = 1;          if (M == 1)             return 0;          while (A > 1) {             // q is quotient             int q = A / M;              int t = M;              // m is remainder now, process             // same as Euclid's algo             M = A % M;             A = t;             t = y;              // Update x and y             y = x - q * y;             x = t;         }          // Make x positive         if (x < 0)             x += m0;          return x;     }      // Driver code     public static void main(String args[])     {         int A = 3, M = 11;          // Function call         System.out.println("Modular multiplicative "                            + "inverse is "                            + modInverse(A, M));     } }  /*This code is contributed by Nikita Tiwari.*/ 
Python
# Iterative Python 3 program to find # modular inverse using extended # Euclid algorithm  # Returns modulo inverse of a with # respect to m using extended Euclid # Algorithm Assumption: a and m are # coprimes, i.e., gcd(A, M) = 1   def modInverse(A, M):     m0 = M     y = 0     x = 1      if (M == 1):         return 0      while (A > 1):          # q is quotient         q = A // M          t = M          # m is remainder now, process         # same as Euclid's algo         M = A % M         A = t         t = y          # Update x and y         y = x - q * y         x = t      # Make x positive     if (x < 0):         x = x + m0      return x   # Driver code if __name__ == "__main__":     A = 3     M = 11      # Function call     print("Modular multiplicative inverse is",           modInverse(A, M))  # This code is contributed by Nikita tiwari. 
C#
// Iterative C# program to find modular // inverse using extended Euclid algorithm using System; class GFG {      // Returns modulo inverse of a with     // respect to m using extended Euclid     // Algorithm Assumption: a and m are     // coprimes, i.e., gcd(A, M) = 1     static int modInverse(int A, int M)     {         int m0 = M;         int y = 0, x = 1;          if (M == 1)             return 0;          while (A > 1) {             // q is quotient             int q = A / M;              int t = M;              // m is remainder now, process             // same as Euclid's algo             M = A % M;             A = t;             t = y;              // Update x and y             y = x - q * y;             x = t;         }          // Make x positive         if (x < 0)             x += m0;          return x;     }      // Driver Code     public static void Main()     {         int A = 3, M = 11;          // Function call         Console.WriteLine("Modular multiplicative "                           + "inverse is "                           + modInverse(A, M));     } }  // This code is contributed by anuj_67. 
JavaScript
<script>  // Iterative Javascript program to find modular // inverse using extended Euclid algorithm  // Returns modulo inverse of a with respect // to m using extended Euclid Algorithm // Assumption: a and m are coprimes, i.e., // gcd(a, m) = 1 function modInverse(a, m) {     let m0 = m;     let y = 0;     let x = 1;      if (m == 1)         return 0;      while (a > 1)     {                  // q is quotient         let q = parseInt(a / m);         let t = m;          // m is remainder now,         // process same as         // Euclid's algo         m = a % m;         a = t;         t = y;          // Update y and x         y = x - q * y;         x = t;     }      // Make x positive     if (x < 0)         x += m0;      return x; }  // Driver Code let a = 3; let m = 11;  // Function call document.write(`Modular multiplicative inverse is ${modInverse(a, m)}`);      // This code is contributed by _saurabh_jaiswal  </script> 
PHP
<?php // Iterative PHP program to find modular // inverse using extended Euclid algorithm  // Returns modulo inverse of a with respect // to m using extended Euclid Algorithm // Assumption: a and m are coprimes, i.e., // gcd(a, m) = 1 function modInverse($A, $M) {     $m0 = $M;     $y = 0;     $x = 1;      if ($m == 1)     return 0;      while ($A > 1)     {                  // q is quotient         $q = (int) ($A / $M);         $t = $M;          // m is remainder now,         // process same as         // Euclid's algo         $M = $A % $M;         $A = $t;         $t = $y;          // Update y and x         $y = $x - $q * $y;         $x = $t;     }      // Make x positive     if ($x < 0)     $x += $m0;      return $x; }      // Driver Code     $A = 3;     $M = 11;      // Function call     echo "Modular multiplicative inverse is: ",                             modInverse($A, $M);          // This code is contributed by Anuj_67 ?> 

Output
Modular multiplicative inverse is 4 

Time Complexity: O(log m)
Auxiliary Space: O(1)


Modular multiplicative inverse when M is prime:

If we know M is prime, then we can also use Fermat's little theorem to find the inverse. 

aM-1 ≡ 1 (mod M)

If we multiply both sides with a-1, we get 

a-1 ≡ a M-2 (mod M)

Below is the implementation of the above approach:

C++
// C++ program to find modular inverse of A under modulo M // This program works only if M is prime. #include <bits/stdc++.h> using namespace std;  // To find GCD of a and b int gcd(int a, int b);  // To compute x raised to power y under modulo M int power(int x, unsigned int y, unsigned int M);  // Function to find modular inverse of a under modulo M // Assumption: M is prime void modInverse(int A, int M) {     int g = gcd(A, M);     if (g != 1)         cout << "Inverse doesn't exist";     else {         // If a and m are relatively prime, then modulo         // inverse is a^(m-2) mode m         cout << "Modular multiplicative inverse is "              << power(A, M - 2, M);     } }  // To compute x^y under modulo m int power(int x, unsigned int y, unsigned int M) {     if (y == 0)         return 1;      int p = power(x, y / 2, M) % M;     p = (p * p) % M;      return (y % 2 == 0) ? p : (x * p) % M; }  // Function to return gcd of a and b int gcd(int a, int b) {     if (a == 0)         return b;     return gcd(b % a, a); }  // Driver code int main() {     int A = 3, M = 11;      // Function call     modInverse(A, M);     return 0; } 
Java
// Java program to find modular // inverse of A under modulo M // This program works only if // M is prime. import java.io.*;  class GFG {      // Function to find modular inverse of a     // under modulo M Assumption: M is prime     static void modInverse(int A, int M)     {         int g = gcd(A, M);         if (g != 1)             System.out.println("Inverse doesn't exist");         else {             // If a and m are relatively prime, then modulo             // inverse is a^(m-2) mode m             System.out.println(                 "Modular multiplicative inverse is "                 + power(A, M - 2, M));         }     }      static int power(int x, int y, int M)     {         if (y == 0)             return 1;         int p = power(x, y / 2, M) % M;         p = (int)((p * (long)p) % M);         if (y % 2 == 0)             return p;         else             return (int)((x * (long)p) % M);     }      // Function to return gcd of a and b     static int gcd(int a, int b)     {         if (a == 0)             return b;         return gcd(b % a, a);     }      // Driver Code     public static void main(String args[])     {         int A = 3, M = 11;          // Function call         modInverse(A, M);     } }  // This code is contributed by Nikita Tiwari. 
Python
# Python3 program to find modular # inverse of A under modulo M  # This program works only if M is prime.  # Function to find modular # inverse of A under modulo M # Assumption: M is prime   def modInverse(A, M):      g = gcd(A, M)      if (g != 1):         print("Inverse doesn't exist")      else:          # If A and M are relatively prime,         # then modulo inverse is A^(M-2) mod M         print("Modular multiplicative inverse is ",               power(A, M - 2, M))  # To compute x^y under modulo M   def power(x, y, M):      if (y == 0):         return 1      p = power(x, y // 2, M) % M     p = (p * p) % M      if(y % 2 == 0):         return p     else:         return ((x * p) % M)  # Function to return gcd of a and b   def gcd(a, b):     if (a == 0):         return b      return gcd(b % a, a)   # Driver Code if __name__ == "__main__":     A = 3     M = 11      # Function call     modInverse(A, M)   # This code is contributed by Nikita Tiwari. 
C#
// C# program to find modular // inverse of a under modulo M // This program works only if // M is prime. using System; class GFG {      // Function to find modular     // inverse of A under modulo     // M Assumption: M is prime     static void modInverse(int A, int M)     {         int g = gcd(A, M);         if (g != 1)             Console.Write("Inverse doesn't exist");         else {             // If A and M are relatively             // prime, then modulo inverse             // is A^(M-2) mod M             Console.Write(                 "Modular multiplicative inverse is "                 + power(A, M - 2, M));         }     }      // To compute x^y under     // modulo M     static int power(int x, int y, int M)     {         if (y == 0)             return 1;          int p = power(x, y / 2, M) % M;         p = (p * p) % M;          if (y % 2 == 0)             return p;         else             return (x * p) % M;     }      // Function to return     // gcd of a and b     static int gcd(int a, int b)     {         if (a == 0)             return b;         return gcd(b % a, a);     }      // Driver Code     public static void Main()     {         int A = 3, M = 11;          // Function call         modInverse(A, M);     } }  // This code is contributed by nitin mittal. 
JavaScript
<script> // Javascript program to find modular inverse of a under modulo m // This program works only if m is prime.  // Function to find modular inverse of a under modulo m // Assumption: m is prime function modInverse(a, m) {     let g = gcd(a, m);     if (g != 1)         document.write("Inverse doesn't exist");     else      {         // If a and m are relatively prime, then modulo         // inverse is a^(m-2) mode m         document.write("Modular multiplicative inverse is "              + power(a, m - 2, m));     } }  // To compute x^y under modulo m function power(x, y, m) {     if (y == 0)         return 1;     let p = power(x, parseInt(y / 2), m) % m;     p = (p * p) % m;      return (y % 2 == 0) ? p : (x * p) % m; }  // Function to return gcd of a and b function gcd(a, b) {     if (a == 0)         return b;     return gcd(b % a, a); }  // Driver code let a = 3, m = 11;  // Function call modInverse(a, m);  // This code is contributed by subham348. </script> 
PHP
<?php // PHP program to find modular  // inverse of A under modulo M // This program works only if M // is prime.  // Function to find modular // inverse of A under modulo // M Assumption: M is prime function modInverse( $A, $M) {     $g = gcd($A, $M);     if ($g != 1)         echo "Inverse doesn't exist";     else     {                  // If A and M are relatively          // prime, then modulo inverse         // is A^(M-2) mod M         echo "Modular multiplicative inverse is "                         , power($A, $M - 2, $M);     } }  // To compute x^y under modulo m function power( $x, $y, $M) {     if ($y == 0)         return 1;     $p = power($x, $y / 2, $M) % $M;     $p = ($p * $p) % $M;      return ($y % 2 == 0)? $p : ($x * $p) % $M; }  // Function to return gcd of a and b function gcd($a, $b) {     if ($a == 0)         return $b;     return gcd($b % $a, $a); }  // Driver Code $A = 3; $M = 11;  // Function call modInverse($A, $M);      // This code is contributed by anuj_67. ?> 

Output
Modular multiplicative inverse is 4 

Time Complexity: O(log M)
Auxiliary Space: O(log M), because of the internal recursion stack.

Applications: 
Computation of the modular multiplicative inverse is an essential step in RSA public-key encryption method.


Next Article
Multiplicative order

A

Ankur
Improve
Article Tags :
  • Mathematical
  • DSA
  • Modular Arithmetic
  • Prime Number
  • number-theory
Practice Tags :
  • Mathematical
  • Modular Arithmetic
  • number-theory
  • Prime Number

Similar Reads

    Modular Arithmetic
    Modular arithmetic is a system of arithmetic for numbers where numbers "wrap around" after reaching a certain value, called the modulus. It mainly uses remainders to get the value after wrap around. It is often referred to as "clock arithmetic. As you can see, the time values wrap after reaching 12
    10 min read
    Modular Exponentiation (Power in Modular Arithmetic)
    Given three integers x, n, and M, compute (x^n) % M (remainder when x raised to the power n is divided by M).Examples : Input: x = 3, n = 2, M = 4Output: 1Explanation: 32 % 4 = 9 % 4 = 1.Input: x = 2, n = 6, M = 10Output: 4Explanation: 26 % 10 = 64 % 10 = 4.Table of Content[Naive Approach] Repeated
    6 min read
    Modular multiplicative inverse
    Given two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that:A X ≡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*0 m
    15+ min read
    Multiplicative order
    In number theory, given an integer A and a positive integer N with gcd( A , N) = 1, the multiplicative order of a modulo N is the smallest positive integer k with A^k( mod N ) = 1. ( 0 < K < N ) Examples : Input : A = 4 , N = 7 Output : 3 explanation : GCD(4, 7) = 1 A^k( mod N ) = 1 ( smallest
    7 min read
    Modular Multiplication
    Given three integers a, b, and M, where M is the modulus. Compute the result of the modular multiplication of a and b under modulo M.((a×b) mod M)Examples:Input: a = 5, b = 3, M = 11Output: 4Explanation: a × b = 5 × 3 = 15, 15 % 11 = 4, so the result is 4.Input: a = 12, b = 15, M = 7Output: 5Explana
    6 min read
    Modular Division
    Given three positive integers a, b, and M, the objective is to find (a/b) % M i.e., find the value of (a × b-1 ) % M, where b-1 is the modular inverse of b modulo M.Examples: Input: a = 10, b = 2, M = 13Output: 5Explanation: The modular inverse of 2 modulo 13 is 7, so (10 / 2) % 13 = (10 × 7) % 13 =
    13 min read
    Modulus on Negative Numbers
    The modulus operator, denoted as %, returns the remainder when one number (the dividend) is divided by another number (the divisor).Modulus of Positive NumbersProblem: What is 7 mod 5?Solution: From Quotient Remainder Theorem, Dividend=Divisor*Quotient + Remainder7 = 5*1 + 2, which gives 2 as the re
    7 min read

    Problems on Modular Arithmetic

    Euler's criterion (Check if square root under modulo p exists)
    Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a
    11 min read
    Find sum of modulo K of first N natural number
    Given two integer N ans K, the task is to find sum of modulo K of first N natural numbers i.e 1%K + 2%K + ..... + N%K. Examples : Input : N = 10 and K = 2. Output : 5 Sum = 1%2 + 2%2 + 3%2 + 4%2 + 5%2 + 6%2 + 7%2 + 8%2 + 9%2 + 10%2 = 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 = 5.Recommended PracticeReve
    9 min read
    How to compute mod of a big number?
    Given a big number 'num' represented as string and an integer x, find value of "num % a" or "num mod a". Output is expected as an integer. Examples : Input: num = "12316767678678", a = 10 Output: num (mod a) ? 8 The idea is to process all digits one by one and use the property that xy (mod a) ? ((x
    4 min read
    Exponential Squaring (Fast Modulo Multiplication)
    Given two numbers base and exp, we need to compute baseexp under Modulo 10^9+7 Examples: Input : base = 2, exp = 2Output : 4Input : base = 5, exp = 100000Output : 754573817In competitions, for calculating large powers of a number we are given a modulus value(a large prime number) because as the valu
    12 min read
    Trick for modular division ( (x1 * x2 .... xn) / b ) mod (m)
    Given integers x1, x2, x3......xn, b, and m, we are supposed to find the result of ((x1*x2....xn)/b)mod(m). Example 1: Suppose that we are required to find (55C5)%(1000000007) i.e ((55*54*53*52*51)/120)%1000000007 Naive Method :  Simply calculate the product (55*54*53*52*51)= say x,Divide x by 120 a
    9 min read
    Modular Multiplication
    Given three integers a, b, and M, where M is the modulus. Compute the result of the modular multiplication of a and b under modulo M.((a×b) mod M)Examples:Input: a = 5, b = 3, M = 11Output: 4Explanation: a × b = 5 × 3 = 15, 15 % 11 = 4, so the result is 4.Input: a = 12, b = 15, M = 7Output: 5Explana
    6 min read
    Difference between Modulo and Modulus
    In the world of Programming and Mathematics we often encounter the two terms "Modulo" and "Modulus". In programming we use the operator "%" to perform modulo of two numbers. It basically finds the remainder when a number x is divided by another number N. It is denoted by : x mod N where x : Dividend
    2 min read
    Modulo Operations in Programming With Negative Results
    In programming, the modulo operation gives the remainder or signed remainder of a division, after one integer is divided by another integer. It is one of the most used operators in programming. This article discusses when and why the modulo operation yields a negative result. Examples: In C, 3 % 2 r
    15+ min read
    Modulo 10^9+7 (1000000007)
    In most programming competitions, we are required to answer the result in 10^9+7 modulo. The reason behind this is, if problem constraints are large integers, only efficient algorithms can solve them in an allowed limited time.What is modulo operation: The remainder obtained after the division opera
    10 min read
    Fibonacci modulo p
    The Fibonacci sequence is defined as F_i = F_{i-1} + F_{i-2} where F_1 = 1 and F_2 = 1 are the seeds. For a given prime number p, consider a new sequence which is (Fibonacci sequence) mod p. For example for p = 5, the new sequence would be 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4 … The minimal zero of the
    5 min read
    Modulo of a large Binary String
    Given a large binary string str and an integer K, the task is to find the value of str % K.Examples: Input: str = "1101", K = 45 Output: 13 decimal(1101) % 45 = 13 % 45 = 13 Input: str = "11010101", K = 112 Output: 101 decimal(11010101) % 112 = 213 % 112 = 101 Approach: It is known that (str % K) wh
    5 min read
    Modular multiplicative inverse from 1 to n
    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 Ex
    9 min read
    Modular exponentiation (Recursive)
    Given three numbers a, b and c, we need to find (ab) % cNow why do “% c” after exponentiation, because ab will be really large even for relatively small values of a, b and that is a problem because the data type of the language that we try to code the problem, will most probably not let us store suc
    6 min read

    Chinese Remainder Theorem

    Introduction to Chinese Remainder Theorem
    We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], .......................x % num[k-1] = rem[k-1] Basically, we are given k numbers which
    7 min read
    Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
    We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[
    11 min read
    Cyclic Redundancy Check and Modulo-2 Division
    Cyclic Redundancy Check or CRC is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver side. An example generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key
    15+ min read
    Using Chinese Remainder Theorem to Combine Modular equations
    Given N modular equations: A ? x1mod(m1) . . A ? xnmod(mn) Find x in the equation A ? xmod(m1*m2*m3..*mn) where mi is prime, or a power of a prime, and i takes values from 1 to n. The input is given as two arrays, the first being an array containing values of each xi, and the second array containing
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences