Euclid's Algorithm
- Tags
- algorithm
Is an algorithm for finding the greatest common divisor of two integers,
def gcd(a, b):
if a < b:
a, b = b, a
while b != 0:
a, b = b, a % b
return a
Procedure
The algorithm proceeds in a series of steps where the output of the last step is used
as the input for the next one. At each step
This series continues until the remainder
Note: if
Proof of Correctness proof
The algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. That is if
, then .
From the Quotient Remainder Theorem we know any number
Now lets summarise the information we have. We have 3 integers
- If
then and so divides both and so . Otherwise (
) we can reduce the problem of to because , , & are all divisible by the same number . If the highest factor between and is then the highest factor between and must also be .Because
this reduction only needs to be applied a finite number of times before we reach and terminate.
This proof was heavily sourced from this stack-overflow answer.