C++ Program to Find LCM

18/04/2024 0 By indiafreenotes

Least Common Multiple (LCM) of two integers is the smallest positive integer that is divisible by both. Unlike the Greatest Common Divisor (GCD), which focuses on division without remainders, the LCM is about finding a common multiple, highlighting a complementary aspect of number theory in computer science and programming.

In C++, calculating the LCM efficiently often involves first finding the GCD, due to the mathematical relationship between them: LCM(a, b) = |a * b| / GCD(a, b) for any two integers a and b, where |a * b| denotes the absolute product of a and b. This relationship allows us to leverage the Euclidean algorithm for GCD calculation as a stepping stone to finding the LCM, demonstrating an elegant interplay between these fundamental concepts.

Implementing the LCM Algorithm in C++

The program below implements a function to find the GCD using the Euclidean algorithm, and then uses this function to calculate the LCM of two numbers. This approach not only showcases the efficiency of utilizing existing algorithms but also emphasizes the importance of building complex functionality from simpler, well-understood operations.

#include <iostream>

using namespace std;

// Function to find the GCD of two integers using the Euclidean algorithm

int gcd(int a, int b) {

    while (b != 0) {

        int remainder = a % b;

        a = b;

        b = remainder;

    }

    return a; // When b is 0, a is the GCD

}

// Function to find the LCM of two integers based on the GCD

int lcm(int a, int b) {

    return (a / gcd(a, b)) * b; // Using the relationship LCM(a, b) = (a * b) / GCD(a, b)

}

int main() {

    int num1, num2;

    // Prompt the user to enter two numbers

    cout << “Enter two integers: “;

    cin >> num1 >> num2;

    // Calculate and display the LCM

    cout << “The LCM of ” << num1 << ” and ” << num2 << ” is ” << lcm(num1, num2) << “.” << endl;

    return 0;

}

 

Detailed Explanation

  • GCD Calculation:

The program first defines a function, gcd, that calculates the Greatest Common Divisor of two numbers using the Euclidean algorithm. This function iteratively reduces the pair of numbers until one of them becomes zero, at which point the other number is the GCD.

  • LCM Calculation:

The lcm function then calculates the Least Common Multiple using the formula LCM(a, b) = (a * b) / GCD(a, b). This formula ensures that we find the smallest positive integer divisible by both a and b, by dividing their absolute product by their GCD. The gcd function is called within the lcm function, showcasing the utility of modular, reusable code.

  • Main Program Flow:

The main function prompts the user for two integers, then calculates and displays their LCM using the lcm function. This demonstrates how to interact with the user, perform calculations using custom functions, and display results.