forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExtended_Euclidean_Algorithm.cpp
61 lines (45 loc) · 1.17 KB
/
Extended_Euclidean_Algorithm.cpp
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
56
57
58
59
60
61
/* 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 <iostream>
#include <tuple>
using namespace std;
// Function for Extended Euclidean algorithm
// It returns multiple values using tuple in C++
tuple<int, int, int> extended_gcd(int a, int b)
{
if (a == 0)
return make_tuple(b, 0, 1);
int gcd, x, y;
// unpack tuple returned by function into variables
tie(gcd, x, y) = extended_gcd(b % a, a);
return make_tuple(gcd, (y - (b/a) * x), x);
}
// main function
int main()
{
/*
Input
30 50
*/
int a = 30;
int b = 50;
tuple<int, int, int> t = extended_gcd(a, b);
int gcd = get<0>(t);
int x = get<1>(t);
int y = get<2>(t);
/*
Output
10
*/
cout << "GCD is " << gcd << endl;
cout << "x = " << x << " y = " << y << endl;
cout << a << "*" << x << " + " << b << "*" << y << " = " << gcd;
return 0;
}