Modular Multiplicative Inverse

Last Updated : 7 Apr, 2026

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.

  • The modular inverse x must be in the range [1, ... , m−1] (it cannot be 0 since n × 0 mod m is never 1).
  • The inverse exists only if gcd(n, m) = 1, i.e., n and m are coprime.

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.

Try It Yourself
redirect icon

[Naive Approach] Iterative Check - O(m) Time and O(1) Space

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:

  • x = 1, (3 × 1) % 11 = 3 not equal to 1
  • x = 2, (3 × 2) % 11 = 6 not equal to 1
  • x = 3, (3 × 3) % 11 = 9 not equal to 1
  • x = 4, (3 × 4) % 11 = 12 % 11 = 1 condition satisfied

Final answer = 4

C++
#include <iostream>
using namespace std;

int modInverse(int n, int m)
{
    // Try all values from 1 to m-1
    for (int x = 1; x < m; x++)
    {
        // Check if (n * x) % m == 1.
        // Note that n and x can be larger
        // than m, so we do modulo before
        // mulityplying
        if (((n % m) * (x % m)) % m == 1)
            return x;
    }

    return -1;
}

int main()
{
    int n = 3, m = 11;

    cout << modInverse(n, m);
    return 0;
}
Java
import java.io.*;

class GFG {

    static int modInverse(int n, int m)
    {
        // Try all values from 1 to m-1
        for (int x = 1; x < m; x++)
        {
            // Check if (n * x) % m == 1.
            // Note that n and x can be larger
            // than m, so we do modulo before
            // mulityplying
            if (((n % m) * (x % m)) % m == 1)
                return x;
        }

        return -1;
    }

    public static void main(String args[])
    {
        int n = 3, m = 11;

        System.out.println(modInverse(n, m));
    }
}
Python
def modInverse(n, m):

    # Try all values from 1 to m-1
    for x in range(1, m):
        
        # Check if (n * x) % m == 1.
        # Note that n and x can be larger
        # than m, so we do modulo before
        # mulityplying
        if ((n % m) * (x % m)) % m == 1:
            return x

    return -1

if __name__ == "__main__":
    n = 3
    m = 11

    print(modInverse(n, m))
C#
using System;

class GFG {

    static int modInverse(int n, int m)
    {
        // Try all values from 1 to m-1
        for (int x = 1; x < m; x++)
        {
            // Check if (n * x) % m == 1.
            // Note that n and x can be larger
            // than m, so we do modulo before
            // mulityplying
            if (((n % m) * (x % m)) % m == 1)
                return x;
        }

        return -1;
    }

    public static void Main()
    {
        int n = 3, m = 11;

        Console.WriteLine(modInverse(n, m));
    }
}
JavaScript
function modInverse(n, m)
{
    // Try all values from 1 to m-1
    for (let x = 1; x < m; x++)
    {
        // Check if (n * x) % m == 1.
        // Note that n and x can be larger
        // than m, so we do modulo before
        // mulityplying
        if (((n % m) * (x % m)) % m == 1)
            return x;
    }

    return -1;
}

// Driver Code
let n = 3;
let m = 11;

console.log(modInverse(n, m));

Output
4

[Expected Approach] Extended Euclidean Algorithm

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 = 1

If 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

C++
#include <iostream>
using namespace std;

// 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;
}

int modInverse(int n, int m)
{
    int x, y;
    int g = gcdExtended(n, m, &x, &y);
    if (g != 1)
        return -1;
    else {

        // m is added to handle negative x
        int res = (x % m + m) % m;
        return res;
    }
}

int main()
{
    int n = 3, m = 11;

    cout << modInverse(n, m);
    return 0;
}
C
#include <stdio.h>

// 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;
}

int modInverse(int n, int m)
{
    int x, y;
    int g = gcdExtended(n, m, &x, &y);
    if (g != 1)
        return -1;
    else {

        // m is added to handle negative x
        int res = (x % m + m) % m;
        return res;
    }
}

int main()
{
    int n = 3, m = 11;

    printf("%d", modInverse(n, m));
    return 0;
}
Java
public class GFG {

    // Function for extended Euclidean Algorithm
    static int gcdExtended(int a, int b, int[] x, int[] y)
    {
        // Base Case
        if (a == 0) {
            x[0] = 0;
            y[0] = 1;
            return b;
        }

        // To store results of recursive call
        int[] x1 = new int[1];
        int[] y1 = new int[1];
        int gcd = gcdExtended(b % a, a, x1, y1);

        // Update x and y using results of recursive call
        x[0] = y1[0] - (b / a) * x1[0];
        y[0] = x1[0];

        return gcd;
    }

    static int modInverse(int n, int m)
    {
        int[] x = new int[1];
        int[] y = new int[1];

        int g = gcdExtended(n, m, x, y);
        if (g != 1)
            return -1;
        else {

            // m is added to handle negative x
            int res = (x[0] % m + m) % m;
            return res;
        }
    }

    public static void main(String[] args)
    {
        int n = 3, m = 11;

        System.out.println(modInverse(n, m));
    }
}
Python
# Function for extended Euclidean Algorithm
def gcdExtended(a, b, x, y):

    # Base Case
    if a == 0:
        x[0] = 0
        y[0] = 1
        return b

    # To store results of recursive call
    x1 = [0]
    y1 = [0]
    gcd = gcdExtended(b % a, a, x1, y1)

    # Update x and y using results of recursive call
    x[0] = y1[0] - (b // a) * x1[0]
    y[0] = x1[0]

    return gcd

def modInverse(n, m):
    x = [0]
    y = [0]

    g = gcdExtended(n, m, x, y)
    if g != 1:
        return -1
    else:
        
        # m is added to handle negative x
        res = (x[0] % m + m) % m
        return res


if __name__ == "__main__":
    n = 3
    m = 11

    print(modInverse(n, m))
C#
using System;

public class GFG {

    // Function for extended Euclidean Algorithm
    static int gcdExtended(int a, int b, int[] x, int[] y)
    {
        // Base Case
        if (a == 0) {
            x[0] = 0;
            y[0] = 1;
            return b;
        }

        // To store results of recursive call
        int[] x1 = new int[1];
        int[] y1 = new int[1];
        int gcd = gcdExtended(b % a, a, x1, y1);

        // Update x and y using results of recursive call
        x[0] = y1[0] - (b / a) * x1[0];
        y[0] = x1[0];

        return gcd;
    }

    // Function to find modulo inverse of n
    static int modInverse(int n, int m)
    {
        int[] x = new int[1];
        int[] y = new int[1];

        int g = gcdExtended(n, m, x, y);
        if (g != 1)
            return -1;
        else {

            // m is added to handle negative x
            int res = (x[0] % m + m) % m;
            return res;
        }
    }

    public static void Main(string[] args)
    {
        int n = 3, m = 11;

        Console.WriteLine(modInverse(n, m));
    }
}
JavaScript
// Function for extended Euclidean Algorithm
function gcdExtended(a, b, x, y)
{

    // Base Case
    if (a === 0) {
        x[0] = 0;
        y[0] = 1;
        return b;
    }

    // To store results of recursive call
    let x1 = [0];
    let y1 = [0];
    let gcd = gcdExtended(b % a, a, x1, y1);

    // Update x and y using results of recursive call
    x[0] = y1[0] - Math.floor(b / a) * x1[0];
    y[0] = x1[0];

    return gcd;
}

function modInverse(n, m)
{
    let x = [0];
    let y = [0];

    let g = gcdExtended(n, m, x, y);
    if (g !== 1)
        return -1;
    else {

        // m is added to handle negative x
        let res = (x[0] % m + m) % m;
        return res;
    }
}

// Driver Code
let n = 3, m = 11;

console.log(modInverse(n, m));

Output
4

2. Iterative Implementation - O(log m) Time and O(1) Space

C++
#include <iostream>
using namespace std;

int gcd(int a, int b)
{
    while (b) {
        int t = b;
        b = a % b;
        a = t;
    }
    return a;
}

int modInverse(int n, int m)
{
    // Check if inverse exists
    if (gcd(n, m) != 1)
        return -1;
        
    int m0 = m;
    int y = 0, x = 1;

    if (m == 1)
        return 0;

    while (n > 1) {
        
        // q is quotient
        int q = n / m;
        int t = m;

        // m is remainder now, process same as Euclid's algo
        m = n % m;
        n = t;
        t = y;

        // Update y and x
        y = x - q * y;
        x = t;
    }

    // Make x positive
    if (x < 0)
        x += m0;

    return x;
}

int main()
{
    int n = 3, m = 11;

    cout << modInverse(n, m);

    return 0;
}
C
#include <stdio.h>

int gcd(int a, int b)
{
    while (b) {
        int t = b;
        b = a % b;
        a = t;
    }
    return a;
}

int modInverse(int n, int m)
{
    // Check if inverse exists
    if (gcd(n, m) != 1)
        return -1;
    
    int m0 = m;
    int y = 0, x = 1;

    if (m == 1)
        return 0;

    while (n > 1) {
        
        // q is quotient
        int q = n / m;
        int t = m;

        // m is remainder now, process same as Euclid's algo
        m = n % m;
        n = t;
        t = y;

        // Update y and x
        y = x - q * y;
        x = t;
    }

    // Make x positive
    if (x < 0)
        x += m0;

    return x;
}

int main()
{
    int n = 3, m = 11;

    printf("%d", modInverse(n, m));

    return 0;
}
Java
class GFG {
    
    static int gcd(int a, int b)
    {
        while (b != 0) {
            int t = b;
            b = a % b;
            a = t;
        }
        return a;
    }

    static int modInverse(int n, int m)
    {
        // Check if inverse exists
        if (gcd(n, m) != 1)
            return -1;
        
        int m0 = m;
        int y = 0, x = 1;

        if (m == 1)
            return 0;

        while (n > 1) {
            
            // q is quotient
            int q = n / m;

            int t = m;

            // m is remainder now, process same as Euclid's algo
            m = n % m;
            n = t;
            t = y;

            // Update y and x
            y = x - q * y;
            x = t;
        }

        // Make x positive
        if (x < 0)
            x += m0;

        return x;
    }

    public static void main(String args[])
    {
        int n = 3, m = 11;

        System.out.println(modInverse(n, m));
    }
}
Python
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

def modInverse(n, m):
    
    # Check if inverse exists
    if gcd(n, m) != 1:
        return -1
    
    m0 = m
    y = 0
    x = 1

    if m == 1:
        return 0

    while n > 1:

        # q is quotient
        q = n // m

        t = m

        # m is remainder now, process same as Euclid's algo
        m = n % m
        n = t
        t = y

        # Update y and x
        y = x - q * y
        x = t

    # Make x positive
    if x < 0:
        x = x + m0

    return x


if __name__ == "__main__":
    n = 3
    m = 11

    print(modInverse(n, m))
C#
using System;

class GFG {
    
    static int gcd(int a, int b)
    {
        while (b != 0) {
            int t = b;
            b = a % b;
            a = t;
        }
        return a;
    }

    static int modInverse(int n, int m)
    {
        // Check if inverse exists
        if (gcd(n, m) != 1)
            return -1;
        
        int m0 = m;
        int y = 0, x = 1;

        if (m == 1)
            return 0;

        while (n > 1) {
            
            // q is quotient
            int q = n / m;

            int t = m;

            // m is remainder now, process same as Euclid's algo
            m = n % m;
            n = t;
            t = y;

            // Update y and x
            y = x - q * y;
            x = t;
        }

        // Make x positive
        if (x < 0)
            x += m0;

        return x;
    }

    public static void Main()
    {
        int n = 3, m = 11;

        Console.WriteLine(modInverse(n, m));
    }
}
JavaScript
function gcd(a, b)
{
    while (b !== 0) {
        let t = b;
        b = a % b;
        a = t;
    }
    return a;
}

function modInverse(n, m)
{
    // Check if inverse exists
    if (gcd(n, m) !== 1)
        return -1;
    
    let m0 = m;
    let y = 0;
    let x = 1;

    if (m === 1)
        return 0;

    while (n > 1)
    {
        // q is quotient
        let q = Math.floor(n / m);
        let t = m;

        // m is remainder now, process same as Euclid's algo
        m = n % m;
        n = 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 n = 3;
let m = 11;

console.log(modInverse(n, m));

Output
4

Modular Multiplicative Inverse When m is Prime

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)

C++
#include <iostream>
using namespace std;

int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}

// Function to compute (x^y) % m using fast exponentiation
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;

    return (y % 2 == 0) ? p : (x * p) % m;
}

// Function to find modular inverse of n under modulo m
// Assumption: m is prime
int modInverse(int n, int m)
{
    if (gcd(n, m) != 1)
        return -1;

    return power(n, m - 2, m);
}

int main()
{
    int n = 3, m = 11;

    cout << modInverse(n, m);

    return 0;
}
Java
class GFG {

    static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }

    // Function to compute (x^y) % m using fast exponentiation
    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);

        return (y % 2 == 0) ? p : (int)((x * (long)p) % m);
    }

    // Function to find modular inverse of n under modulo m
    // Assumption: m is prime
    static int modInverse(int n, int m)
    {
        if (gcd(n, m) != 1)
            return -1;

        return power(n, m - 2, m);
    }

    public static void main(String args[])
    {
        int n = 3, m = 11;

        System.out.println(modInverse(n, m));
    }
}
Python
def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)

# Function to compute (x^y) % m using fast exponentiation
def power(x, y, m):
    if y == 0:
        return 1

    p = power(x, y // 2, m) % m
    p = (p * p) % m

    return p if y % 2 == 0 else (x * p) % m

# Function to find modular inverse of n under modulo m
# Assumption: m is prime
def modInverse(n, m):
    if gcd(n, m) != 1:
        return -1

    return power(n, m - 2, m)


if __name__ == "__main__":
    n = 3
    m = 11

    print(modInverse(n, m))
C#
using System;

class GFG {

    static int gcd(int a, int b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }

    // Function to compute (x^y) % m using fast exponentiation
    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;

        return (y % 2 == 0) ? p : (x * p) % m;
    }

    // Function to find modular inverse of n under modulo m
    // Assumption: m is prime
    static int modInverse(int n, int m)
    {
        if (gcd(n, m) != 1)
            return -1;

        return power(n, m - 2, m);
    }

    public static void Main()
    {
        int n = 3, m = 11;

        Console.WriteLine(modInverse(n, m));
    }
}
JavaScript
function gcd(a, b)
{
    if (a === 0)
        return b;
    return gcd(b % a, a);
}

// Function to compute (x^y) % m using fast exponentiation
function power(x, y, m)
{
    if (y === 0)
        return 1;

    let p = power(x, Math.floor(y / 2), m) % m;
    p = (p * p) % m;

    return (y % 2 === 0) ? p : (x * p) % m;
}

// Function to find modular inverse of n under modulo m
// Assumption: m is prime
function modInverse(n, m)
{
    if (gcd(n, m) !== 1)
        return -1;

    return power(n, m - 2, m);
}

// Driver code
let n = 3, m = 11;

console.log(modInverse(n, m));

Output
4

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

Comment