Modular inverse

The Modular Inverse of a number $$a$$ is a number that will give $$1 \mod{b}$$.

The Algorithm
Given a number $$x$$ and $$y$$, if they are co-primes (which is trivially true if one of them is a prime), then there are integer solutions to:

$$ax + by = 1$$

Taking the mod of y on both sides, we get

$$ax \equiv 1 \mod{y}$$

(we can also get $$by \equiv 1 \mod{x}$$ similarly.)

$$a$$ is therefore the modular inverse of $$x$$ in respect to $$y$$.

We can calculate $$a$$ using the Extended Euclidean 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}$$