-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgcd.cpp
More file actions
57 lines (55 loc) · 1.08 KB
/
gcd.cpp
File metadata and controls
57 lines (55 loc) · 1.08 KB
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
#include <iostream>
using namespace std;
//Time Complexity: O(log(n))
// int main(){
// int a = 15, b = 0;
// int gcd = 1;
// if (a == 0)
// cout << b;
// else if (b == 0)
// cout << a;
// else if (a == b)
// cout << a;
// else{
// for (int i = 1; i < min(a, b); i++)
// {
// if (a % i == 0 && b % i == 0)
// {
// gcd = i;
// }
// }
// cout << gcd;
// }
// }
//Euclid's Algorithm
int gcd(int a, int b){
while(a>0 && b>0 ){
if (a>b){
a=a%b;
}else{
b=b%a;
}
}
if (a==0) return b;
return a;
}
int gcdRec(int a, int b){ //gcd recursion
if (b==0) return a;
else{
gcdRec(b,a%b);
}
}
int LCM(int a, int b){
int GCD=gcd(a,b);
return (a*b)/GCD;
}
int main(){
int a=20, b=28;
cout<<gcd(a,b)<<endl;
cout<<LCM(a,b)<<endl;
if (a>b){
cout<<gcdRec(a,b);
}else{
cout<<gcdRec(b,a);
}
}