118 views
LCM of two numbers in C++
To find the least common multiple (LCM) of two numbers in C++, you can use the following code snippet. You can either implement a function to calculate the LCM or use the standard library’s std::lcm
function introduced in C++17:
C++
#include <iostream>
#include <numeric> // Required for std::lcm (C++17 and later)
int calculateLCM(int a, int b) {
// Calculate LCM using the formula: LCM(a, b) = (a * b) / GCD(a, b)
return (a * b) / std::__gcd(a, b);
}
int main() {
int num1, num2;
std::cout << "Enter the first number: ";
std::cin >> num1;
std::cout << "Enter the second number: ";
std::cin >> num2;
int lcm = calculateLCM(num1, num2);
std::cout << "LCM of " << num1 << " and " << num2 << " is " << lcm << std::endl;
return 0;
}
This code defines a function calculateLCM
to compute the LCM of two numbers using the formula LCM(a, b) = (a * b) / GCD(a, b), where GCD is the greatest common divisor. It then uses this function in the main
function to calculate and print the LCM of two user-input numbers.