TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
least_common_multiple.cpp File Reference
#include <cassert>
#include <iostream>
Include dependency graph for least_common_multiple.cpp:

Go to the source code of this file.

Functions

unsigned int gcd (unsigned int x, unsigned int y)
 
unsigned int lcm (unsigned int x, unsigned int y)
 
void tests ()
 
int main ()
 

Detailed Description

Copyright 2020

Author
tjgurwara99

A basic implementation of LCM function

Definition in file least_common_multiple.cpp.

Function Documentation

◆ 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 // 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}
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()

int main ( void )

Main function

Definition at line 78 of file least_common_multiple.cpp.

78 {
79 tests();
80 return 0;
81}
void tests()

◆ tests()

void tests ( )

Function for testing the lcm() functions with some assert statements.

Definition at line 50 of file least_common_multiple.cpp.

50 {
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}
unsigned int lcm(unsigned int x, unsigned int y)