Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
C Program for Extended Euclidean algorithms?
Here we will see the extended Euclidean algorithm implemented using C. The extended Euclidean algorithm is also used to get the GCD. This finds integer coefficients of x and y like below −
??+?? = gcd(?,?)
Here in this algorithm it updates the value of gcd(a, b) using the recursive call like this − gcd(b mod a, a). Let us see the algorithm to get the idea
Algorithm
EuclideanExtended(a, b, x, y)
begin if a is 0, then x := 0 y := 1 return b end if gcd := EuclideanExtended(b mod a, a, x1, y1) x := y1 – (b/a)*x1 y := x1 return gcd end
Example
#include <stdio.h>
int EuclideanExtended(int a, int b, int* x, int* y) {
if (a == 0) {
*x = 0;
*y = 1;
return b;
}
int xtemp, ytemp; // To store results of recursive call
int res = EuclideanExtended(b % a, a, &xtemp, &ytemp);
*x = ytemp - (b / a) * xtemp;
*y = xtemp;
return res;
}
int main() {
int x, y;
int a = 60, b = 25;
int res = EuclideanExtended(a, b, &x, &y);
printf("gcd(%d, %d) = %d", a, b, res);
}
Output
gcd(60, 25) = 5
Advertisements
