gcd and lcm in c++

The greatest common divisor (gcd) and least common multiple (lcm) are two important mathematical concepts in number theory. In C++, you can calculate the gcd and lcm using the built-in library functions or by implementing your own algorithms.

Calculating gcd using the built-in library function:

To calculate the gcd using the built-in library function in C++, you need to include the <numeric> header file and use the gcd() function from the std namespace. The gcd() function takes two integer arguments and returns their gcd.

Here is an example of calculating the gcd using the built-in library function:

#include <iostream>
#include <numeric>

int main() {
    int a = 12, b = 18;
    int result = std::gcd(a, b);
    std::cout << "GCD of " << a << " and " << b << " is " << result << std::endl;
    return 0;
}

Output:

GCD of 12 and 18 is 6

Calculating lcm using the built-in library function:

To calculate the lcm using the built-in library function in C++, you also need to include the <numeric> header file and use the lcm() function from the std namespace. The lcm() function takes two integer arguments and returns their lcm.

Here is an example of calculating the lcm using the built-in library function:

#include <iostream>
#include <numeric>

int main() {
    int a = 12, b = 18;
    int result = std::lcm(a, b);
    std::cout << "LCM of " << a << " and " << b << " is " << result << std::endl;
    return 0;
}

Output:

LCM of 12 and 18 is 36

Implementing gcd and lcm algorithms:

If you want to implement your own gcd and lcm algorithms in C++, you can use the Euclidean algorithm for gcd and the formula lcm(a, b) = (a * b) / gcd(a, b) for lcm.

Here is an example of implementing gcd and lcm algorithms:

#include <iostream>

int gcd(int a, int b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

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

int main() {
    int a = 12, b = 18;
    int result_gcd = gcd(a, b);
    int result_lcm = lcm(a, b);
    std::cout << "GCD of " << a << " and " << b << " is " << result_gcd << std::endl;
    std::cout << "LCM of " << a << " and " << b << " is " << result_lcm << std::endl;
    return 0;
}

Output:

GCD of 12 and 18 is 6
LCM of 12 and 18 is 36

In the above example, the gcd() function uses recursive calls to calculate the gcd using the Euclidean algorithm. The lcm() function calculates the lcm using the formula mentioned earlier.

I hope this explanation helps! Let me know if you have any further questions.