![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Implement Extended Euclidean Algorithm
The Extended Euclidean Algorithm is just a another way of calculating GCD of two numbers. It has extra variables to compute ax + by = gcd(a, b). It's more efficient to use in a computer program
Algorithm
Begin Declare variable a, b, x and y gcdExtended(int a, int b, int *x, int *y) if (a == 0) *x = 0; *y = 1; return b; Take two variables to store the result Update x and y using results of recursive call End
Example Code
#include <bits/stdc++.h> using 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 x, y; int a = 35, b = 15; cout<<"gcd "<<gcdExtended(a, b, &x, &y); return 0; }
Output
gcd 5
Advertisements