# Extended Euclidean algorithm (builtin function), very fast
# Allows us to compute inverse of a mod m
xgcd(3,26)
# xgcd(a,m) = (d,b,c) s.t.
# ab + mc = d = gcd(a,m)
3 * 9 + 26 * (-1) == 1
xgcd(15, 26)
7*15 % 26
# So inverse of 15 mod 26 is 7
# CHALLENGE: finish this, using modular reduction at each step
def exp_mod(a,e,m):
"""Return a^e % m """
# Don't just do: return (a^e) % m
prod = 1
for i in range(e):
prod = (prod * a) % m # reduce mod m at each step
# prevents numbers from getting too big
return prod
exp_mod(2,10,7)
exp_mod(3,3,41)
exp_mod(3,10000001,67)
# Want: modular exponentiation algorithm that takes roughly num_digits(e) steps
# to compute a^e mod b
# CHALLENGE: finish this, using "repeated squaring"
def exp_mod_powtwo(a,n,m):
"""Return a^(2^n) % m """
# Don't do this: return exp_mod(a,2^n,m)
prod = a % m # start with a%m, rather than 1
for i in range(n):
prod = (prod * prod) % m # square, and reduce mod m
return prod
exp_mod_powtwo(3,4,7)
exp_mod_powtwo(2,5,11)
exp_mod(2,2^5,11)
exp_mod_powtwo(2,1000,11)
exp_mod(2,2^1000,11) # should compute same thing as above, but runs into error
# because numbers are too big