TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
least_common_multiple.cpp
Go to the documentation of this file.
1
8
#include <cassert>
9
#include <iostream>
10
16
unsigned
int
gcd
(
unsigned
int
x,
unsigned
int
y) {
17
if
(x == 0) {
18
return
y;
19
}
20
if
(y == 0) {
21
return
x;
22
}
23
if
(x == y) {
24
return
x;
25
}
26
if
(x > y) {
27
// The following is valid because we have checked whether y == 0
28
29
unsigned
int
temp = x / y;
30
return
gcd
(y, x - temp * y);
31
}
32
// Again the following is valid because we have checked whether x == 0
33
34
unsigned
int
temp = y / x;
35
return
gcd
(x, y - temp * x);
36
}
37
43
unsigned
int
lcm
(
unsigned
int
x,
unsigned
int
y) {
44
return
x /
gcd
(x, y) * y;
45
}
46
50
void
tests
() {
51
// First test on lcm(5,10) == 10
52
assert(((
void
)
"LCM of 5 and 10 is 10 but lcm function gives a different "
53
"result.\n"
,
54
lcm
(5, 10) == 10));
55
std::cout <<
"First assertion passes: LCM of 5 and 10 is "
<<
lcm
(5, 10)
56
<< std::endl;
57
58
// Second test on lcm(2,3) == 6 as 2 and 3 are coprime (prime in fact)
59
assert(((
void
)
"LCM of 2 and 3 is 6 but lcm function gives a different "
60
"result.\n"
,
61
lcm
(2, 3) == 6));
62
std::cout <<
"Second assertion passes: LCM of 2 and 3 is "
<<
lcm
(2, 3)
63
<< std::endl;
64
65
// Testing an integer overflow.
66
// The algorithm should work as long as the result fits into integer.
67
assert(((
void
)
"LCM of 987654321 and 987654321 is 987654321 but lcm function"
68
" gives a different result.\n"
,
69
lcm
(987654321, 987654321) == 987654321));
70
std::cout <<
"Third assertion passes: LCM of 987654321 and 987654321 is "
71
<<
lcm
(987654321, 987654321)
72
<< std::endl;
73
}
74
78
int
main
() {
79
tests
();
80
return
0;
81
}
tests
void tests()
Definition
least_common_multiple.cpp:50
gcd
unsigned int gcd(unsigned int x, unsigned int y)
Definition
least_common_multiple.cpp:16
lcm
unsigned int lcm(unsigned int x, unsigned int y)
Definition
least_common_multiple.cpp:43
main
int main()
Definition
least_common_multiple.cpp:78
math
least_common_multiple.cpp
Generated by
1.12.0