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)
Pause and ponder. Make you you understand why that works.
Example:
Calculate gcd(24,15)
24=1⋅15+915=1⋅9+69=1⋅6+36=2⋅3+0⇒3=gcd(24,15)
Code
defmy_gcd(a,b):# If a < b swap themif a < b: a, b = b, a# If we encounter 0 return aif b ==0:return aelse: r = a % breturnmy_gcd(b, r)print(my_gcd(24, 15))# 3
Exercises:
Pick 2 numbers and calculate their gcdby hand.
Implement the algorithm in Python / Sage and play with it. Do not copy paste the code
Extended Euclidean Algorithm
This section needs to be expanded a bit.
Bezout's identity
Let d=gcd(a,b). Then there exists u,v such that au+bv=d
The extended euclidean algorithm aims to find d=gcd(a,b), and u,vgiven a,b
# In sage we have the `xgcd` functiona =24b =15g, 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