arrow-left

All pages
gitbookPowered by GitBook
1 of 1

Loading...

Euclidean Algorithm

hashtag
Introduction

Although we have functions that can compute our gcdโก\gcdgcdeasily 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.

hashtag
Euclidean Algorithm

Important Remark

If and then . Therefore

hashtag
Algorithm

We write the following:

Or iteratively until we find a . Then we stop

Now here's the trick:

If then divides

circle-check

Pause and ponder. Make you you understand why that works.

Example:

Calculate

Code

Exercises:

  1. Pick 2 numbers and calculate their by hand.

  2. Implement the algorithm in Python / Sage and play with it. Do not copy paste the code

hashtag
Extended Euclidean Algorithm

triangle-exclamation

This section needs to be expanded a bit.

Bezout's identity

Let . Then there exists such that

The extended euclidean algorithm aims to find given

a=bโ‹…q+ra = b \cdot q + ra=bโ‹…q+r
d=gcdโก(a,b)d = \gcd(a, b)d=gcd(a,b)
dโˆฃrd | rdโˆฃr
gcdโก(a,b)=gcdโก(b,r)\gcd(a, b) = \gcd(b, r)gcd(a,b)=gcd(b,r)
a=q0โ‹…b+r0b=q1โ‹…r0+r1r0=q2โ‹…r1+r2โ‹ฎrnโˆ’2=rnโˆ’1โ‹…qnโˆ’1+rnrn=0 a = q_0 \cdot b + r_0 \\ b = q_1 \cdot r_0 + r_1 \\ r_0 = q_2 \cdot r_1 + r_2 \\ \vdots \\ r_{n-2} = r_ {n-1} \cdot q_{n - 1} + r_n \\ r_n = 0a=q0โ€‹โ‹…b+r0โ€‹b=q1โ€‹โ‹…r0โ€‹+r1โ€‹r0โ€‹=q2โ€‹โ‹…r1โ€‹+r2โ€‹โ‹ฎrnโˆ’2โ€‹=rnโˆ’1โ€‹โ‹…qnโˆ’1โ€‹+rnโ€‹rnโ€‹=0
rkโˆ’2=qkโ‹…rkโˆ’1+rkr_{k-2} = q_k \cdot r_{k-1} + r_krkโˆ’2โ€‹=qkโ€‹โ‹…rkโˆ’1โ€‹+rkโ€‹
000
gcdโก(a,b)=gcd(b,r0)=gcd(r0,r1)=โ‹ฏ=gcdโก(rnโˆ’2,rnโˆ’1)=rnโˆ’1=d\gcd(a, b) = gcd(b, r_0) = gcd(r_0, r_1) = \dots = \gcd(r_{n-2}, r_{n-1}) = r_{n-1} = dgcd(a,b)=gcd(b,r0โ€‹)=gcd(r0โ€‹,r1โ€‹)=โ‹ฏ=gcd(rnโˆ’2โ€‹,rnโˆ’1โ€‹)=rnโˆ’1โ€‹=d
d=gcdโก(a,b)d = \gcd(a, b)d=gcd(a,b)
ddd
r0,r1,...rnโˆ’1r_0, r_1, ... r_{n-1}r0โ€‹,r1โ€‹,...rnโˆ’1โ€‹
gcdโก(24,15)\gcd(24, 15)gcd(24,15)
24=1โ‹…15+915=1โ‹…9+69=1โ‹…6+36=2โ‹…3+0โ‡’3=gcdโก(24,15)24 = 1 \cdot 15 + 9 \\ 15 = 1 \cdot 9 + 6 \\ 9 = 1 \cdot 6 + 3 \\ 6 = 2 \cdot 3 + 0 \Rightarrow 3 = \gcd(24, 15) 24=1โ‹…15+915=1โ‹…9+69=1โ‹…6+36=2โ‹…3+0โ‡’3=gcd(24,15)
gcdโก\gcdgcd
d=gcdโก(a,b)d = \gcd(a, b)d=gcd(a,b)
u,vu, vu,v
au+bv=dau + bv = dau+bv=d
d=gcdโก(a,b),ย andย u,vd = \gcd(a, b), \text{ and }u, vd=gcd(a,b),ย andย u,v
a,ba, ba,b
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