Modular inverse

The inverse of a number $$a$$ modulo $$m$$ is a number $$x$$ such that $$ax \equiv 1 \mod{m}$$. It exists (and is unique if exists) if and only $$a$$ and $$m$$ are relatively prime (that is, $$\gcd(a, m) = 1$$). In particular, if $$m$$ is a prime, every non-zero element of $$Z_m$$ has an inverse (thus making it an algebraic structure known as field).

Conventionally, the mathematical notation used for inverses is $$a^{-1} \mod{m}$$.

In modular arithmetic the inverse of $$a$$ is analogous to the number $$1/a$$ in usual real-number arithmetic. If you have a product $$c = ab$$, and one of the factors has an inverse, you can get the other factor by multiplying the product by that inverse: $$a = c b^{-1} \mod{m}$$. Thus you can perform division in ring $$Z_m$$.

Finding the inverse
We can rewrite the defining equation of modular inverses as an equivalent linear diophantine equation: $$ax + my = 1$$. This equation has a solution whenever $$\gcd(a, m) = 1$$, and we can find such solution $$(x, y)$$ by means of the extended Euclidean algorithm.

Then $$a^{-1} \equiv x \mod{m}$$, and also $$m^{-1} \equiv y \mod{a}$$.

The following Python code implements this algorithm:

Alternative algorithm
If you happen to know $\phi(m)$, you can also compute the inverses using Euler's theorem, which states that $$a^{\phi(m)} \equiv 1 \mod{m}$$. By multiplying both sides of this equation by $$a$$'s modular inverse, we can deduce that: $$a^{-1} \equiv a^{\phi(m) - 1} \mod{m}$$.

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

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

Applications
Suppose we need to calculate $$\frac{a}{b} \mod{p}$$. If $$b$$ and $$p$$ are co-primes (or if one of them is a prime), then we can calculate the modular inverse $$b'$$ of $$b$$.

Thus:

$$\frac{a}{b} \mod{P} \equiv ab' \mod{P}$$