|
| 1 | +/** |
| 2 | + * Copyright 2020 @author tjgurwara99 |
| 3 | + * @file |
| 4 | + * |
| 5 | + * A basic implementation of LCM function |
| 6 | + */ |
| 7 | + |
| 8 | +#include <cassert> |
| 9 | +#include <iostream> |
| 10 | + |
| 11 | +/** |
| 12 | + * Function for finding greatest common divisor of two numbers. |
| 13 | + * @params two integers x and y whose gcd we want to find. |
| 14 | + * @return greatest common divisor of x and y. |
| 15 | + */ |
| 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 | + 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 | + int temp = y / x; |
| 35 | + return gcd(x, y - temp * x); |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * Function for finding the least common multiple of two numbers. |
| 40 | + * @params integer x and y whose lcm we want to find. |
| 41 | + * @return lcm of x and y using the relation x * y = gcd(x, y) * lcm(x, y) |
| 42 | + */ |
| 43 | +unsigned int lcm(unsigned int x, unsigned int y) { return x * y / gcd(x, y); } |
| 44 | + |
| 45 | +/** |
| 46 | + * Function for testing the lcm() functions with some assert statements. |
| 47 | + */ |
| 48 | +void tests() { |
| 49 | + // First test on lcm(5,10) == 10 |
| 50 | + assert(((void)"LCM of 5 and 10 is 10 but lcm function gives a different " |
| 51 | + "result.\n", |
| 52 | + lcm(5, 10) == 10)); |
| 53 | + std::cout << "First assertion passes: LCM of 5 and 10 is " << lcm(5, 10) |
| 54 | + << std::endl; |
| 55 | + |
| 56 | + // Second test on lcm(2,3) == 6 as 2 and 3 are coprime (prime in fact) |
| 57 | + assert(((void)"LCM of 2 and 3 is 6 but lcm function gives a different " |
| 58 | + "result.\n", |
| 59 | + lcm(2, 3) == 6)); |
| 60 | + std::cout << "Second assertion passes: LCM of 2 and 3 is " << lcm(2, 3) |
| 61 | + << std::endl; |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Main function |
| 66 | + */ |
| 67 | +int main() { |
| 68 | + tests(); |
| 69 | + return 0; |
| 70 | +} |
0 commit comments