Let \(a,b\in\mathbb{Z}\) be positive integers $a,b\in\mathbb Z$ with \(a\le b\) which are co-prime. The algorithm \(\operatorname{invmod}(a,b)\) calculates correctly the multiplicative inverse $a^{-1}$ in the ring of congruences $\mathbb Z_b,$ i.e. for which $$a\cdot a^{-1}\equiv 1\mod b.$$ In particular, if $b=p$ is a prime number, this is the unique inverse of $a$ modulo $b$ in the field of congruences $\mathbb Z_p.$
The algorithm requires \(\mathcal O(\log |b|)\) (worst case and average case) division operations, which corresponds to \(\mathcal O(\log^2 |b|)\) bit operations.
def invmod(a, b): res = gcdext(a, b) if res[^0] != 1: raise NotCoPrimeException(a, b) else: if res[^1] < 0: res[^1] = res[^1] + (abs(res[^1]) // b + 1) * b return res[^1]
print(invmod(16, 21))
Proofs: 1
Propositions: 1