Input: two positive integers b and a.
Output: the inverse of a modulo b, $a^{-1}$ mod b, if it exists.
Initialize: $b_0 = b$, $a_0 = a$, $r_0 = 0$, $r = 1$, $q = \left\lfloor \frac{b_0}{a_0} \right\rfloor$, $s = b_0 - q a_0$.
Step 1: While $s > 0$ do
Step 1.1: temp = $r_0 - qr$.
Step 1.2: If temp ? 0 then temp = temp mod b.
Step 1.2.1: Else temp = b - ((-temp) mod b).
Step 1.3: $r_0 = r$.
Step 1.4: r = temp.
Step 1.5: $b_0 = a_0$.
Step 1.6: $a_0 = s$.
Step 1.7: $q = \left\lfloor \frac{b_0}{a_0} \right\rfloor$.
Step 1.8: $s = b_0 - q a_0$.
Step 2: End While
Step 3: If $a_0 \neq 1$ then output a has no inverse modulo b
Step 3.1: Else return $a^{-1} = r$ mod b.