In this post, we will learn how to find the L.C.M. of two numbers using C++ programming language.
The LCM (least common multiple) of two numbers a and b is the smallest positive integer that is perfectly divisible by both a and b.
Algorithm to create the respective code
We will find the lcm of two numbers using the standard method, so without wasting time let’s begin with the code.
C++ code to find the L.C.M. of two numbers
// C++ Program to Find LCM of Two Numbers #include <iostream> using namespace std; int main(){ int a, b, lcm; // Asking for input cout << "Enter the first number: "; cin >> a; cout << "Enter the second number: "; cin >> b; lcm = (a > b) ? a : b; //greatest of the two while(1){ if ((lcm % a == 0) && (lcm % b == 0)){ cout << "LCM of two numbers: " << lcm; break; } ++lcm; } return 0; }
Output of the above code
Explanation of the above code
- In this program, we have declared three variables of data type int named a, b and lcm.
- The user is then asked to enter two integers. The value of these two integers will be stored in the named variables a and b.
- Now we check whether the maximum value is divisible by both a and b or not. If so, the value of the lcm variables will be printed and our program will exit.
- If not, then lcm is incremented by 1 and the same process continues until lcm is exactly divisible by both a and b.