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
16unsigned 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
43unsigned int lcm(unsigned int x, unsigned int y) {
44 return x / gcd(x, y) * y;
45}
46
50void 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
78int main() {
79 tests();
80 return 0;
81}
void tests()
unsigned int gcd(unsigned int x, unsigned int y)
unsigned int lcm(unsigned int x, unsigned int y)