Although we have functions that can compute our gcdeasily it's important enough that we need to give and study an algorithm for it: the euclidean algorithm.
It's extended version will help us calculate modular inverses which we will define a bit later.
Euclidean Algorithm
Important Remark
If a=b⋅q+rand d=gcd(a,b) then d∣r. Therefore gcd(a,b)=gcd(b,r)
def my_gcd(a, b):
# If a < b swap them
if a < b:
a, b = b, a
# If we encounter 0 return a
if b == 0:
return a
else:
r = a % b
return my_gcd(b, r)
print(my_gcd(24, 15))
# 3
# In sage we have the `xgcd` function
a = 24
b = 15
g, u, v = xgcd(a, b)
print(g, u, v)
# 3 2 -3
print(u * a + v * b)
# 3 -> because 24 * 2 - 15 * 3 = 48 - 45 = 3