LCM
The least / lowest common multiple (LCM) of two or more than two numbers is the smallest number (not zero) which is a multiple of all of the numbers.
Logic
Let declare one temporary variable lcm by 1, we are going to use this variable to store LCM.
Here we are calculating LCM of two user given numbers, after taking both the numbers (num1, num2) from the user, we have to find out the maximum number, we store the maximum one in variable max and also assign the value of max to the variable i.
Now we start one infinite loop while(1), inside the loop we have to check if both the numbers can completely divide max value. If yes then we terminate the loop with break statement and assign current value of “i” to lcm, otherwise, continue the loop.
Once the loop is over, simply print the variable lcm containing the lowest common multiple of num1 and num2.
Program
#include <iostream> using namespace std; int main() { int i, num1, num2, max, lcm=1; // Take two numbers from user cout << "Enter any two number : "; cin >> num1 >> num2; // Find the max number max = (num1 > num2) ? num1 : num2; i = max; while(1) { if((i % num1) == 0 && (i % num2) == 0) { lcm = i; break; } i += max; } cout << endl << "LCM of " << num1 << " and " << num2 << " : " << lcm; return 0; }
Output
Enter any two number : 6 24
LCM of 6 and 24 : 24