Modular inverse

From Algorithmist
Jump to navigation Jump to search

The inverse of a number modulo is a number such that . It exists (and is unique if exists) if and only and are relatively prime (that is, ). In particular, if is a prime, every non-zero element of has an inverse (thus making it an algebraic structure known as field).

Conventionally, the mathematical notation used for inverses is .

In modular arithmetic the inverse of is analogous to the number in usual real-number arithmetic. If you have a product , and one of the factors has an inverse, you can get the other factor by multiplying the product by that inverse: . Thus you can perform division in ring .

Finding the inverse[edit]

We can rewrite the defining equation of modular inverses as an equivalent linear diophantine equation: . This equation has a solution whenever , and we can find such solution by means of the extended Euclidean algorithm.

Then , and also .

The following Python code implements this algorithm.

# Iterative Algorithm (xgcd)
def iterative_egcd(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q,r = b//a,b%a; m,n = x-u*q,y-v*q # use x//y for floor "floor division"
        b,a, x,y, u,v = a,r, u,v, m,n
    return b, x, y

# Recursive Algorithm
def recursive_egcd(a, b):
    """Returns a triple (g, x, y), such that ax + by = g = gcd(a,b).
       Assumes a, b >= 0, and that at least one of them is > 0.
       Bounds on output values: |x|, |y| <= max(a, b)."""
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = recursive_egcd(b % a, a)
        return (g, x - (b // a) * y, y)

egcd = iterative_egcd  # or recursive_egcd(a, m)

def modinv(a, m):
    g, x, y = egcd(a, m) 
    if g != 1:
        return None
    else:
        return x % m

Alternative algorithm[edit]

If you happen to know , you can also compute the inverses using Euler's theorem, which states that . By multiplying both sides of this equation by 's modular inverse, we can deduce that: .

And so you can utilize repeated squaring algorithm to quickly find the inverse.

This algorithm can be useful if is a fixed number in your program (so, you can hardcode a precomputed value of ), or if is a prime number, in which case . In general case, however, computing is equivalent to factoring, which is a hard problem, so prefer using the extended GCD algorithm.

Applications[edit]

Suppose we need to calculate . If and are co-primes (or if one of them is a prime), then we can calculate the modular inverse of .

Thus: