Euclidean Algorithm
Last updated
Was this helpful?
Was this helpful?
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