« previous | Wednesday, April 27, 2011 | next »
Extended Euclidean Algorithm
Find the greatest common devisor for two nonnegative, different integers and :
def euclidean a, b
while (b != 0) do
a, b = b, a%b
end
return a
end
Proving Algorithm Correctness
Find an invariant of the loop (a property that holds through each iteration). This invariant and should imply that the result is the GCD of and .
Let (set of all linear combinations of and over all integers.
If contains , then
Lemma 1: If , then
Proof: The set contains the remainer , since , where the quotient . Thus if , then .
On the other hand, since . Therefore by antisymmetry, .
Q.E.D.
Suppose that the algorithm returns the value . By Lemma 1, (where contains all multiples of ). Therefore is a divisor of and .
Since , we can find the integers and such that .
Therefore, each common divisor of and divides , hence is the greatest common divisor of and .
Q.E.D.