Algorithms_in_C++ 1.0.0
Set of 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:

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

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.
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)
Definition least_common_multiple.cpp:16
Here is the call graph for this function:

◆ 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)
43 {
44 return x / gcd(x, y) * y;
45}
Here is the call graph for this function:

◆ main()

int main ( void )

Main function

78 {
79 tests();
80 return 0;
81}
void tests()
Definition least_common_multiple.cpp:50
Here is the call graph for this function:

◆ tests()

void tests ( )

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

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}
T endl(T... args)
unsigned int lcm(unsigned int x, unsigned int y)
Definition least_common_multiple.cpp:43
Here is the call graph for this function: