Euclidean Algorithm Proof
📂Number TheoryEuclidean Algorithm Proof
Algorithm
For two integers a≥b, gcd(a,b) can be calculated as follows.
Pseudocode
Algorithm: Euclidean method | | |
---|
In | Given integers a,b. | |
1. | r0←a | |
2. | r1←b | |
3. | while ri+1=0 | |
4. | Continue to find qi and a new ri+1 such that the following is satisfied.ri−1=ri⋅qi+ri+1,(ri>ri+1) | |
5. | i←i+1 | |
6. | end while | |
Out | Obtain the greatest common divisor gcd(a,b) of a and b. | |
Theorem
Let’s define a:=r−1 and b:=r0 that satisfy the recurrence ri−1=qi+1⋅ri+ri+1 for ri<ri+1. The least common multiple of n that satisfies rn+1=0 is as follows.
rn=gcd(a,b)
This algorithm can find the answer within at most 2log2(b)+1 times.
Explanation
The algorithm known as the Euclidean Algorithm makes it very efficient to calculate the greatest common divisor. It shines more as the numbers get bigger since it provides the answer without having to factorize the numbers one by one.
The algorithm summarized above is purely a translation of Euclid’s original method, but the code can be written more easily.
Proof
a=r0=b=r1=ri=rt−1=b⋅q1+r1r2⋅q2+r3⋮ri+1⋅qi+1+ri+2⋮rt⋅qt
Let’s assume. Given the condition
ri−1=ri⋅qi+ri+1,(ri>ri+1)
we can see that the divisors of ri−1 and ri are also the divisors of ri+1. Therefore,
gcd(ri−1,ri)=gcd(ri,ri+1)
it is. On the other hand, thinking about rt−1=rt⋅qt,(rt+1=0),
gcd(rt−1,rt)=gcd(rt⋅qt,rt)=rt
Now, let’s calculate the required time, namely the number of iterations needed. Before that, we must show that ri+2<21ri.
- If ri+1≤21ri,
ri+2<ri+1≤21ri - If ri+1>21ri,
ri=ri+1⋅1+ri+2
thus,
ri+2=ri−ri+1<ri−21ri≤21ri
it is. To summarize,
ri+2<21ri
and by the above inequality,
b=r1>2⋅r3>22⋅r5>⋯>2k⋅r2k+1
it is. To summarize,
b>2k⋅r2k+1
Meanwhile, because 2k≥b, r2k+1<1 must be true, which means
r2k+1=0
it is. Also, since t+1≤2k+1,
t≤2k
In other words, the total number of iterations to end the algorithm is less or equal to t,
t≤2k=2(k−1)+2<2log2(b)+2
thus, the number of iterations required is at most as follows.
2log2(b)+1
■
Implementation
Below is the implementation of the Euclidean method in R code. The first is a version that directly translates the algorithm, and the bottom is a version that cuts out unnecessary parts and tidies up.
gcd<-function(a,b)
{
if (b>a) {i=b; b=a; a=i;}
i=2
r=numeric(0)
r[1]=b
r[2]=a%%b
while(r[i]!=0)
{
r[i+1]=r[i-1]%%r[i]
i=i+1
}
return(r[i-1])
}
gcd <- function(a, b) {
if (b>a) {i=b; b=a; a=i;}
while(b) {
temp = b
b = a %% b
a = temp
}
return(a)
}