Greatest Common Divisor (GCD) and Least Common Multiple (LCM) Calculator in CPLUSPLUS

 

Introduction

The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both numbers without leaving a remainder. The Least Common Multiple (LCM) of two numbers is the smallest number that is a multiple of both numbers. These two mathematical concepts are useful in various applications such as simplifying fractions, solving number theory problems, and more.

Objective

The goal of this program is to calculate both the GCD and LCM of two given integers using C++ programming. The user will input two numbers, and the program will output their GCD and LCM.

Program Code (C++)

#include 
using namespace std;

// Function to calculate GCD using Euclidean algorithm
int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

// Function to calculate LCM using the relationship between GCD and LCM
int lcm(int a, int b) {
    return (a * b) / gcd(a, b);  // LCM formula: LCM(a, b) = (a * b) / GCD(a, b)
}

int main() {
    int num1, num2;

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

    // Calculate GCD and LCM
    int resultGCD = gcd(num1, num2);
    int resultLCM = lcm(num1, num2);

    // Output the results
    cout << "Greatest Common Divisor (GCD) of " << num1 << " and " << num2 << " is: " << resultGCD << endl;
    cout << "Least Common Multiple (LCM) of " << num1 << " and " << num2 << " is: " << resultLCM << endl;

    return 0;
}

Explanation of Program Structure

The program is designed with two main functions:

  • gcd(int a, int b): This function calculates the Greatest Common Divisor of two numbers using the Euclidean algorithm. It repeatedly divides the larger number by the smaller number until the remainder is zero. The last non-zero remainder is the GCD.
  • lcm(int a, int b): This function calculates the Least Common Multiple of two numbers using the formula: LCM(a, b) = (a * b) / GCD(a, b).

The program starts by prompting the user to enter two integers. It then calculates the GCD and LCM by calling the respective functions and displays the results.

How to Run the Program

To run this program:

    1. Ensure that you have a C++ compiler installed on your system (e.g., GCC, Visual Studio).
    2. Create a new C++ file (e.g., gcd_lcm.cpp) and paste the provided code into it.
    3. Compile the code using your C++ compiler. For example, using GCC:
g++ gcd_lcm.cpp -o gcd_lcm
    1. Run the compiled program:
./gcd_lcm
  1. Follow the on-screen instructions to input two integers. The program will output their GCD and LCM.
© 2024 Learn Programming

 

Leave a Reply

Your email address will not be published. Required fields are marked *