You are right that the Extended Euclidean Algorithm solves this task. However you don't need to call it n
times - you only need it once. Check http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
Here is an imperative python algorithm from http://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm
def 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
b,a, x,y, u,v = a,r, u,v, m,n
return b, x, y
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
return None # modular inverse does not exist
else:
return x % m
O(1) space and around O(log n) time in the worst case.
Now, to divide modulo n
, we have by definition
def moddiv(a, b, n):
binv = modinv(b, n)
if not binv:
return None
return a * binv % n