C++ Program to find LCM of two numbers

Write a C++ program to calculate and display the Least Common Multiple of two given integers. 

Input and Output Examples

Example 1:

  • Input: 12, 18
    Output: The LCM of 12 and 18 is 36.

Example 2:

  • Input: 25, 15
    Output: The LCM of 25 and 15 is 75.

Algorithm to Find LCM of two numbers

  1. Start the program.
  2. Prompt the user to enter two integers.
  3. Read the integers.
  4. Calculate the greatest common divisor (GCD) of the two numbers using the Euclidean algorithm.
  5. Calculate the LCM using the relationship between GCD and LCM, which is LCM(a,b)=GCD(a,b)∣a×b∣​.
  6. Display the LCM.
  7. End the program.

Below is the C++ code for finding the LCM:

cpp
#include <iostream> 
using namespace std; 

// Function to compute the GCD of two numbers
int gcd(int a, int b) {
    // Continue until the remainder is 0
    while (b != 0) {
        int remainder = a % b;
        a = b;
        b = remainder;
    }
    return a; // The GCD is the last non-zero remainder
}

// Main function to drive the program
int main() {
    // Declare variables to store the two numbers
    int num1, num2;

    // Prompt the user for two numbers
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;

    // Calculate GCD
    int gcdValue = gcd(num1, num2);

    // Calculate LCM using the relationship between GCD and LCM
    int lcm = (num1 * num2) / gcdValue;

    // Display the LCM
    cout << "The LCM of " << num1 << " and " << num2 << " is " << lcm << "." << endl;

    // Ending the program
    return 0;
}

Testing the Program with Different Input Values

  • Input: 100, 40
  • Output: The LCM of 100 and 40 is 200.
  • Input: 7, 5
  • Output: The LCM of 7 and 5 is 35.

Programming

2886

285

Related Articles