Skip to content

Commit 0ea8d09

Browse files
committed
Added gcd and lcm algos
1 parent e9da770 commit 0ea8d09

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

.vscode/settings.json

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"files.associations": {
3+
"iostream": "cpp"
4+
}
5+
}
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Implements Algorithms for GCD and LCM.
2+
#include <iostream>
3+
using namespace std;
4+
5+
int gcd(int a, int b)
6+
{
7+
if (b == 0)
8+
return a;
9+
return gcd(b, a % b);
10+
}
11+
12+
int gcdExtended(int a, int b, int *x, int *y)
13+
{
14+
// Base case.
15+
if (a == 0)
16+
{
17+
*x = 0;
18+
*y = 1;
19+
return b;
20+
}
21+
22+
int x1, y1;
23+
int gcd = gcdExtended(b % a, a, &x1, &y1);
24+
25+
*x = y1 - (b / a) * x1;
26+
*y = x1;
27+
28+
return gcd;
29+
}
30+
31+
int lcm(int a, int b)
32+
{
33+
return (a * b) / gcd(a, b);
34+
}
35+
36+
int main()
37+
{
38+
int a = 15, b = 20;
39+
int x, y;
40+
cout << "GCD of " << a << " and " << b << " is: " << gcd(b, a);
41+
cout << endl;
42+
cout << "GCD of " << a << " and " << b << " is: " << gcdExtended(a, b, &x, &y);
43+
cout << endl;
44+
cout << "LCM of " << a << " and " << b << " is: " << lcm(b, a);
45+
cout << endl;
46+
return 0;
47+
}

0 commit comments

Comments
 (0)