# 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), where
# d= gcd(a,m) = ab + mc
1 == 3*9 + 26*(-1)
xgcd(15,26)
# In above, 7 is inverse of 15 mod 26
7*15 % 26
xgcd(124124892173, 123891237273231) # fast
# CHALLENGE: finish this function
def exp_mod(a,e,b):
"""Compute a^e mod b"""
# don't just do: return (a^e) % b
prod = 1
for i in range(e):
prod = (prod * a) % b # reduce mod m at each step,
# prevents numbers from getting too big
return prod
# test on 2^10000 % 7, exp_mod(2,10000,7)
exp_mod(2,12,7)
exp_mod(2, 10000, 7)
%%time
exp_mod(2,19237300,7)
# 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, b):
"""Return a^(2^n) mod b"""
prod = a % b # start with a%b, rather than 1
for i in range(n):
prod = (prod * prod) % b # square, and reduce mod b
return prod
exp_mod_powtwo(3,3,7)
exp_mod_powtwo(2, 10, 17)
exp_mod(2, 2^10, 17)
exp_mod_powtwo(2, 1000, 17) # same as above, but faster