Google News
logo
C++ Program to Find LCM
In the following example of C++ program to find the LCM (Least Common Multiple) of two numbers :
Program :
#include <iostream>

int main() {
    int num1, num2, max, lcm;
    std::cout << "Enter two positive integers: ";
    std::cin >> num1 >> num2;
    max = (num1 > num2) ? num1 : num2;
    while (true) {
        if (max % num1 == 0 && max % num2 == 0) {
            lcm = max;
            break;
        }
        max++;
    }
    std::cout << "LCM of " << num1 << " and " << num2 << " is " << lcm << std::endl;
    return 0;
}
Output :
Enter two positive integers: 4 7
LCM of 4 and 7 is 28
This program takes two inputs from the user num1 and num2, which represent the two numbers whose LCM is to be found.

It then uses a while loop to repeatedly increment a variable max until it is divisible by both num1 and num2 without a remainder. This is done by checking whether max is evenly divisible by num1 and num2 using the modulus operator (%).

Once a value of max that satisfies this condition is found, the program sets lcm to max and exits the loop. Finally, the program outputs the LCM of num1 and num2 to the console using std::cout.