Programs

C++ Program to Find LCM

C++ Program to Find LCM

The Least Common Multiple (LCM) of two integers (a) and (b) is the smallest positive integer that is divisible by both (a) and (b).

Here’s a Turbo C++ program to find the LCM of two numbers:

#include <iostream.h>
#include <conio.h>

// Function to find GCD of two numbers
int gcd(int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}

// Function to find LCM of two numbers
int lcm(int a, int b) {
    return (a * b) / gcd(a, b);
}

void main() {
    clrscr();  // Clear the screen (specific to Turbo C++)

    int num1, num2;

    // Input two numbers from the user
    cout << "Enter first number: ";
    cin >> num1;

    cout << "Enter second number: ";
    cin >> num2;

    // Call the lcm function and display the result
    cout << "LCM of " << num1 << " and " << num2 << " is " << lcm(num1, num2) << endl;

    getch();  // Wait for user input (specific to Turbo C++)
}

To compile and run this program in Turbo C++:

  1. Open Turbo C++.
  2. Create a new file and copy-paste the above code into it.
  3. Save the file.
  4. Compile the code (usually by pressing Alt + F9).
  5. Run the program (usually by pressing Ctrl + F9).

After entering two integers, the program will display their LCM using the formula based on their GCD.