# Extended Euclidean algorithm Implementation in C, C++ and Python

The extended Euclidean algorithm is an extension to the Euclidean algorithm, which computes, besides the greatest common divisor of integers a and b, the coefficients of Bézout’s identity, that is integers x and y such that

ax + by = gcd(a,b)

For example,

gcd(30, 50) = 10
Here x = 2 y = -1 as 30*2 + 50*-1 = 10

gcd(2740, 1760) = 20
Here, x = 9 y = -14 as 2740*9 + 1760*-14 = 20

The gcd is the only number that can simultaneously satisfy this equation and divide the inputs. The extended Euclid’s algorithm will allows us to simultaneously calculate the gcd and coefficients of the Bézout’s identity x and y at no extra cost.

Following is the implementation of Extended Euclidean algorithm in C, C++ and Python.

Output:

GCD is 10
x = 2, y = -1

## C++

Output:

GCD is 10
x = 2 y = -1
30*2 + 50*-1 = 10

## Python

Output:

10 2 -1

The extended Euclidean algorithm is particularly useful when a and b are co-prime, since x is the modular multiplicative inverse of a modulo b, and y is the modular multiplicative inverse of b modulo a. Both extended Euclidean algorithms are widely used in cryptography. The computation of the modular multiplicative inverse is an essential step in RSA public-key encryption algorithm.

(2 votes, average: 5.00 out of 5)