Extended Euclidean Algorithm is an extension of the Euclidean Algorithm that computes the greatest common divisor (GCD) of integers and . GCD is the largest integer that divides both and without any remainder.
Recall the division algorithm from grade school. When we divide an integer from a non-zero integer, there exists integers and such that:
where
is known as the quotient and is the remainder. The Euclidean Algorithm repeatedly applies the division algorithm to find the GCD of integers and . We repeatedly divide the divisor by the remainder until the remainder is zero. The last non-zero remainder is the greatest common divisor. Below is an example of how to use the Euclidean Algorithm to find the GCD of 56 and 15:
Below is a Python program that recursively computes the GCD via the Euclidean Algorithm:
def GCD(a, b):if a == 0:return breturn GCD(b%a, a)print("GCD(25,10)=", GCD(25,10))print("GCD(63,57)=", GCD(63,57))print("GCD(7,9)=", GCD(7,9))print("GCD(4,14)=", GCD(4,16))
In addition to computing GCD, Extended Euclidean Algorithm also finds integers and such that .
Bézout’s Identity guarantees the existence of and .
Extended Euclidean Algorithm finds and by using back substitutions to recursively rewrite the division algorithm equation until we end up with the equation that is a linear combination of our initial numbers. Below is an example of how to use the Extended Euclidean Algorithm to find the GCD of 56 and 15 to find and such that
Below is a Python program that recursively computes the integers and and the GCD via the Extended Euclidean Algorithm:
def extendedGCD(a, b):if a == 0:return b, 0, 1gcd, s1, t1 = extendedGCD(b%a, a)s,t = updateCoeff(a,b,s1,t1)return gcd, s, tdef updateCoeff(a,b,s,t):return (t - (b//a) * s, s)gcd, s, t = extendedGCD(25,10)print("extendedGCD(25,10)-> ", "GCD:", gcd,"\ts:", s, "\tt:",t)gcd, s, t = extendedGCD(63,57)print("extendedGCD(63,57)-> ", "GCD:", gcd,"\ts:", s, "\tt:",t)gcd, s, t = extendedGCD(7,9)print("extendedGCD(7,9)-> ", "GCD:", gcd,"\ts:", s, "\tt:",t)
In the above code, we find the GCD in the same way as the Euclidean Algorithm but in addition, we update the values of and using the updateCoeff()
function after each recursive call.
Free Resources