
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- C Program for Extended Euclidean algorithms?
- Python Program for Extended Euclidean algorithms
- C++ Program to Implement Kadane’s Algorithm
- C++ Program to Implement Johnson’s Algorithm
- Euclidean Algorithm for calculating GCD in JavaScript
- C++ Program to Implement the RSA Algorithm
- C++ Program to Implement Coppersmith Freivald’s Algorithm
- C++ Program to Implement Modular Exponentiation Algorithm
- C++ Program to Implement Nearest Neighbour Algorithm
- C++ Program to Implement Expression Tree Algorithm
- C++ Program to Implement Interpolation Search Algorithm
- C program to implement Euclid’ s algorithm
- C++ Program to Implement Levenshtein Distance Computing Algorithm
- C++ Program to Implement Dijkstra’s Algorithm Using Set
- C++ Program to Implement The Edmonds-Karp Algorithm

Advertisements