C Program for Extended Euclidean algorithms
Last Updated :
22 Jun, 2022
GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors.
C
#include <stdio.h>
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;
int g = gcdExtended(a, b, &x, &y);
printf ("gcd(%d, %d) = %d", a, b, g);
return 0;
}
|
Time Complexity: O(Log min(a, b))
Auxiliary Space: O(1)
Please refer complete article on Basic and Extended Euclidean algorithms for more details!
Share your thoughts in the comments
Please Login to comment...