
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Extended Euclidean Algorithm in C++
The extended Euclidean algorithms find the greatest common divisor(GCD) of two numbers in the form of ax + by = gcd(a,b). This expression is also known as Bezout's Identity. The extended Euclidean algorithm is an extension of the Euclid algorithm that is also used to find the GCD of two numbers using repetitive division.
In this article, we have two numbers and our task is to implement the extended Euclidean algorithm to find the GCD of these two numbers in C++.
Steps To Implement Extended Euclidean Algorithm
The steps to implement an extended Euclidean algorithm are as follows:
- We have defined a function gcdExtended() that accepts four arguments: the integers 'a' and 'b' and the reference variables to store a and b.
- The gcdExtended() function calculates the GCD of two numbers using the Extended Euclidean Algorithm. It also finds the integer coefficients i.e. x and y using a*x + b*y = gcd(a, b).
- We are using a recursive function so we have defined the base case as if a == 0. We have set the values of x = 0, and y = 1 in the base case and return b which is the GCD of both numbers. The values of 'x' and 'y' are later used to find the value of coefficients of a and b.
- The gcdExtended() function is recursively called to find the GCD of b % a and a and is stored in the variable gcd.
- After the recursive call, we update the 'x' and 'y' based on the 'a' and 'b' using x = y1 - (b / a) * x1 and y = x1. These are the coefficients of 'a' and 'b'.
- The function then returns the GCD of the two numbers.
Extended Euclidean Algorithm Using C++
Here is the C++ implementation to calculate the GCD of two numbers using the extended Euclidean algorithm:
#includeusing namespace std; int gcdExtended(int a, int b, int &x, int &y) { if (a == 0) { x = 0; y = 1; return b; } int x1, y1; int gcd = gcdExtended(b % a, a, x1, y1); x = y1 - (b / a) * x1; y = x1; return gcd; } int main() { int a = 35, b = 15; int x, y; int gcd = gcdExtended(a, b, x, y); cout << "GCD of " << a << " and " << b << " is: " << gcd << endl; return 0; }
The output of the above code is:
GCD of 35 and 15 is: 5
Advertisements