C++ Code Example: least common multiple

The code is an implementation of the Least Common Multiple (LCM) function in C++. The LCM is defined as the smallest positive integer that is divisible by two or more numbers. The code consists of two functions: the first function is a function for calculating the greatest common divisor (gcd) of two numbers, and the second function is for calculating the LCM of two numbers.

The gcd function is an implementation of the Euclidean algorithm, which is a recursive algorithm used to find the greatest common divisor of two numbers. The gcd function takes two parameters, a and b, and returns the greatest common divisor of the two numbers. The function uses the following conditions to calculate the gcd:

  1. If a is equal to 0, then the gcd of a and b is b.
  2. If b is equal to 0, then the gcd of a and b is a.
  3. If a is greater than b, then the gcd of a and b is equal to the gcd of a - b and b.
  4. If b is greater than a, then the gcd of a and b is equal to the gcd of a and b - a.

The lcm function is used to calculate the LCM of two numbers. It takes two parameters, a and b, and returns the LCM of the two numbers. The function calculates the LCM by dividing the product of a and b by the gcd of a and b.

Finally, the main function is used to test the lcm function. It sets the values of a and b to 10 and 6, respectively, and prints the LCM of the two numbers.

#include <iostream>
using namespace std;

static int gcd(int a, int b) {
    if (a == 0) {
        return b;
    } else if (b == 0) {
        return a;
    } else if (a > b) {
        return gcd(a - b, b);
    } else {
        return gcd(a, b - a);
    }
}

static int lcm(int a,int b) {
    return a * b / gcd( a, b);
}

int main() {
    int a = 10, b = 6;

    cout << "Least common multiple is: " << lcm(a, b) << endl;

    return 0;
}
Output
Least common multiple is: 30