The least common multiple (LCM) of two or more integers is the smallest positive integer that is divisible by all of them.
In this tutorial, we will discuss how to write a C++ program to find the LCM of two integers.
To find the LCM of two integers, we need to use the following formula:
LCM(a,b) = (a*b)/GCD(a,b)
where a and b are two integers and GCD(a,b) is their greatest common divisor. To find the GCD of two integers, we can use the Euclidean algorithm.
Let’s start by writing a function to find the GCD of two integers:
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
This function takes two integers as input and recursively calls itself with the second integer as the first argument and the remainder of the first integer divided by the second integer as the second argument until the second integer becomes zero.
When the second integer becomes zero, the function returns the first integer as the GCD.
Now, let’s write a function to find the LCM of two integers using the above formula:
int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
This function takes two integers as input, calls the gcd function to find their GCD, and returns their LCM using the above formula.
To test our functions, we can write a simple main function:
int main() {
int a = 10;
int b = 15;
int result = lcm(a, b);
std::cout << "LCM of " << a << " and " << b << " is " << result << std::endl;
return 0;
}
This main function initializes two integers a and b with values 10 and 15, calls the lcm function with these integers as input, and prints the result to the console.
When we run the above program, we should see the following output:
LCM of 10 and 15 is 30
This confirms that our program is working correctly and is able to find the LCM of two integers using the given formula.
In conclusion, finding the LCM of two integers can be done using the formula LCM(a,b) = (a*b)/GCD(a,b) where GCD(a,b) is the greatest common divisor of a and b.




