#include <cassert>
#include <iostream>
Go to the source code of this file.
|
unsigned int | gcd (unsigned int x, unsigned int y) |
|
unsigned int | lcm (unsigned int x, unsigned int y) |
|
void | tests () |
|
int | main () |
|
Copyright 2020
- Author
- tjgurwara99
A basic implementation of LCM function
Definition in file least_common_multiple.cpp.
◆ gcd()
unsigned int gcd |
( |
unsigned int | x, |
|
|
unsigned int | y ) |
Function for finding greatest common divisor of two numbers. @params two integers x and y whose gcd we want to find.
- Returns
- greatest common divisor of x and y.
Definition at line 16 of file least_common_multiple.cpp.
16 {
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
28
29 unsigned int temp = x / y;
30 return gcd(y, x - temp * y);
31 }
32
33
34 unsigned int temp = y / x;
35 return gcd(x, y - temp * x);
36}
unsigned int gcd(unsigned int x, unsigned int y)
◆ lcm()
unsigned int lcm |
( |
unsigned int | x, |
|
|
unsigned int | y ) |
Function for finding the least common multiple of two numbers. @params integer x and y whose lcm we want to find.
- Returns
- lcm of x and y using the relation x * y = gcd(x, y) * lcm(x, y)
Definition at line 43 of file least_common_multiple.cpp.
43 {
44 return x /
gcd(x, y) * y;
45}
◆ main()
◆ tests()
Function for testing the lcm() functions with some assert statements.
Definition at line 50 of file least_common_multiple.cpp.
50 {
51
52 assert(((void)"LCM of 5 and 10 is 10 but lcm function gives a different "
53 "result.\n",
55 std::cout <<
"First assertion passes: LCM of 5 and 10 is " <<
lcm(5, 10)
56 << std::endl;
57
58
59 assert(((void)"LCM of 2 and 3 is 6 but lcm function gives a different "
60 "result.\n",
62 std::cout <<
"Second assertion passes: LCM of 2 and 3 is " <<
lcm(2, 3)
63 << std::endl;
64
65
66
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}
unsigned int lcm(unsigned int x, unsigned int y)