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.


Download   Run Code


GCD is 10
x = 2, y = -1


Download   Run Code


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


Download   Run Code


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.

References: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of