-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGcdLcm.cpp
85 lines (66 loc) · 1.07 KB
/
GcdLcm.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <stdlib.h>
using namespace std;
int main (const int argc, const char* const argv[])
{
if (argc < 3) {
cerr << "Error: Unable to compute GCD and/or LCM because of insufficient arguments." << endl;
return -1;
}
if (argc > 3) {
cerr << "Warning: Expecting two command-line arguments." << endl;
return -1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int LCM = 1;
int GCD = 1;
int g = 1;
if (a <= 0 || b <= 0) {
cerr << "Error: Unable to compute GCD and/or LCM because of invalid input." << endl;
return -1;
}
if (a%b==0)
{
g=b;
GCD = abs(g);
}
if (b%a==0)
{
g=a;
GCD = abs(g);
}
while (g != 0) {
if (a>b)
{
g = a%b;
a = b;
b = g;
if (g!=0)
{
GCD = abs(g);
}
}
if (a==b)
{
g=0;
GCD = a;
}
if (a<b)
{
g = b%a;
b = a;
a = g;
if (g!=0)
{
GCD = abs(g);
}
}
}
a = atoi(argv[1]);
b = atoi(argv[2]);
LCM = abs((a/GCD)*b);
cout << "GCD (" << a << ", " << b << ") = " << GCD << endl;
cout << "LCM (" << a << ", " << b << ") = " << LCM << endl;
return 0;
}