forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Extended_Euclidean_Algorithm.c
55 lines (45 loc) · 1.03 KB
/
Extended_Euclidean_Algorithm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* Extended Euclidean Algorithm
==============================
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.
GCD(a,b) = ax + by
If we can find the value of x and y then we can easily find the
value of GCD(a,b) by replacing (x,y) with their respective values.
*/
#include <stdio.h>
// C function for extended Euclidean Algorithm
int gcdExtended(int a, int b, int *x, int *y)
{
// Base Case
if (a == 0)
{
*x = 0;
*y = 1;
return b;
}
// To store results of recursive call
int x1, y1;
// Recursion
int gcd = gcdExtended(b%a, a, &x1, &y1);
/* Update x and y using results of recursive call */
*x = y1 - (b/a) * x1;
*y = x1;
return gcd;
}
// Driver Program
/* Input
50 20
*/
int main()
{
int x, y;
int a = 50, b = 20;
int g = gcdExtended(a, b, &x, &y);
/* Output
10
GCD of 50 and 20 is 10
*/
printf("gcdExtended(%d, %d) = %d", a, b, g);
return 0;
}