CPP Tutorials

# Finding the LCM of Two Numbers in CPP

## Introduction

In this article, we delve into the concept of finding the Least Common Multiple (LCM) of two numbers using C++. LCM is a fundamental mathematical concept that helps us determine the smallest common multiple shared by two given numbers. We’ll explore why LCM is essential, as it plays a crucial role in various real-world scenarios, like scheduling tasks or combining fractions. This article covers what LCM is, why it’s needed, and most importantly, how to calculate it using C++ programming. By the end, you’ll have a clear understanding of LCM’s significance and the practical steps to implement it in your programs.

## Algorithm to Find LCM of Two Numbers

Here’s a step-by-step algorithm to find the Least Common Multiple (LCM) of two numbers in easy-to-understand language:

Algorithm to Find LCM of Two Numbers:

• Input:
• Accept two positive integers, let’s call them ‘`num1`‘ and ‘`num2`‘, for which you want to find the LCM.
• Identify the Larger Number:
• Compare ‘`num1`‘ and ‘`num2`‘ to determine which one is larger. Assign the larger value to a variable ‘`larger`‘.
• Initialization:
• Initialize a variable ‘`lcm`‘ to store the LCM. Set ‘`lcm`‘ to the value of ‘`larger`‘.
• Finding LCM:
• Create a loop that continues until both ‘`num1`‘ and ‘`num2`‘ are equal to 1.
• Inside the loop, check if ‘`lcm`‘ is divisible by both ‘`num1`‘ and ‘`num2`‘ without any remainder.
• If both conditions are met, exit the loop as you’ve found the LCM.
• If not, increment ‘`lcm`‘ by the value of ‘`larger`‘.
• Output:
• After exiting the loop, display the value of ‘`lcm`‘ as the Least Common Multiple of the two numbers.

Example:

Let’s say you want to find the LCM of 12 and 18 using this algorithm:

• Input: `num1 = 12` and `num2 = 18`.
• The larger number is `18`.
• Initialize `lcm = 18`.
• Start looping:
• 18 % 12 != 0, so increment `lcm` by 18: `lcm = 36`.
• 36 % 12 == 0 and 36 % 18 == 0, so exit the loop.
• Output: The LCM of 12 and 18 is 36.

By following this algorithm, you can find the LCM of any two positive integers. Just replace ‘`num1`‘ and ‘`num2`‘ with the numbers you want to find the LCM for.

## Program to Find LCM of Two Numbers Using if Statement.

Finding the LCM of Two Numbers Using an If Statement

In this program, we will write a Python code to find the Least Common Multiple (LCM) of two numbers using the concept of if statements. The LCM is the smallest multiple that both input numbers share. We’ll break down the code into simple steps and provide explanations along the way.

Step 1: Input the Two Numbers
We start by taking input from the user for the two numbers for which we want to find the LCM.

Step 2: Find the Maximum Number
We need to find the larger of the two input numbers because the LCM cannot be greater than the maximum input number.

Step 3: Use an If Statement to Find the LCM
We’ll use an if statement to iterate through multiples of the maximum number until we find a multiple that is also divisible by the second input number. This multiple will be the LCM.

Step 4: Output the LCM
Once we find the LCM, we’ll display it as the output.

Example Code:

C++
``````#include <iostream>
using namespace std;

int main() {
// Step 1: Input the Two Numbers
int num1, num2;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;

// Step 2: Find the Maximum Number
int max_num = max(num1, num2);

// Step 3: Use an If Statement to Find the LCM
while (true) {
if (max_num % num1 == 0 && max_num % num2 == 0) {
int lcm = max_num;
break;
}
max_num++;
}

// Step 4: Output the LCM
cout << "The LCM of " << num1 << " and " << num2 << " is: " << max_num << endl;

return 0;
}``````

Example Output:

C++
``````Enter the first number: 6
Enter the second number: 8
The LCM of 6 and 8 is: 24``````

Code Explanation:

• We start by taking input for the two numbers using the ‘`input()`‘ function and converting them to integers using ‘`int()`‘.
• The larger of the two numbers is determined using the ‘`max()`‘ function and stored in the variable ‘`max_num`‘.
• The ‘`while`‘ loop is used to iterate through multiples of ‘`max_num`‘ until we find a multiple that is divisible by both ‘`num1`‘ and ‘`num2`‘.
• The ‘`if`‘ statement inside the loop checks if the current ‘`max_num`‘ is divisible by both ‘`num1`‘ and ‘`num2`‘.
• When a valid LCM is found, the loop is terminated using the ‘`break`‘ statement.
• Finally, the calculated LCM is printed as output using the ‘`print()`‘ function.

## Program to Get LCM of Two Numbers using GCD (While Loop)

Understanding the Concept:

• The Least Common Multiple (LCM) of two numbers is the smallest multiple that both numbers share.
• We can find the LCM of two numbers using their GCD. The relationship is: LCM(a, b) = (a * b) / GCD(a, b).

Steps to Find LCM using GCD:

1. Start by including the necessary C++ libraries: `iostream` and `algorithm`.
2. Define a function to calculate the GCD of two numbers using the Euclidean algorithm.
3. Within the main function:
• Input the two numbers for which you want to find the LCM.
• Calculate the GCD of the two numbers using the function from step 2.
• Calculate the LCM using the formula: LCM = (num1 * num2) / GCD.
• Print the calculated LCM.

Code Example:
Here’s a simple C++ program that implements the above steps:

C++
``````#include <iostream>
#include <algorithm>

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;
}

int main() {
int num1, num2;

cout << "Enter two numbers: ";
cin >> num1 >> num2;

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

// Calculate LCM
int lcm_result = (num1 * num2) / gcd_result;

cout << "LCM of " << num1 << " and " << num2 << " is: " << lcm_result << endl;

return 0;
}``````

Output:

C++
``````Enter two numbers: 12 18
LCM of 12 and 18 is: 36``````

Explanation:

• The program starts by including the necessary libraries and defining the `gcd` function.
• The main function takes two numbers as input from the user.
• It calculates the GCD of the two numbers using the `gcd` function.
• Using the GCD, it calculates the LCM using the formula `(num1 * num2) / gcd_result`.
• Finally, it prints the calculated LCM.

## Program to Get the LCM of Two Numbers Using GCD (Recursion)

Step 1: Understand the LCM and GCD concepts.

• LCM: The smallest multiple that is evenly divisible by both numbers.
• GCD: The largest number that divides both numbers without leaving a remainder.

Step 2: Import the necessary libraries and declare a function for GCD.

C++
``````#include <iostream>
using namespace std;

int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}``````

Step 3: Calculate LCM using GCD.

• LCM = (num1 * num2) / GCD(num1, num2)
C++
``````int lcm(int num1, int num2) {
return (num1 * num2) / gcd(num1, num2);
}``````

Step 4: Main function to take user input and display results.

C++
``````int main() {
int num1, num2;

cout << "Enter first number: ";
cin >> num1;

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

int result = lcm(num1, num2);
cout << "LCM of " << num1 << " and " << num2 << " is: " << result << endl;

return 0;
}``````

Step 5: Compile and run the program.

• Input:
C++
``````Enter first number: 12
Enter second number: 18``````
• Output:
C++
``LCM of 12 and 18 is: 36``

Explanation of the code:

• The code starts by including the necessary header files and using the `namespace std`.
• The `gcd` function is defined to calculate the GCD of two numbers using recursion.
• Base case: When `b` becomes 0, the GCD is found and `a` is returned.
• Recursive case: The function is called again with `b` and `a % b` as arguments.
• The `lcm` function calculates the LCM using the formula `(num1 * num2) / gcd(num1, num2)`.
• In the `main` function, user input for two numbers is taken using `cin`.
• The LCM is calculated using the `lcm` function and displayed as output.

Key Points:

• GCD is calculated using the Euclidean algorithm through the `gcd` function.
• LCM is calculated by dividing the product of the two numbers by their GCD in the `lcm` function.
• User inputs are taken for the two numbers in the `main` function.
• The calculated LCM is displayed as output.

## Program to Get the LCM of Array Elements using Function and While Loop

Program to Get the LCM of Array Elements using Function and While Loop in C++

Introduction:
In this program, we’ll be writing a C++ program to find the Least Common Multiple (LCM) of elements in an array using a user-defined function and a while loop. LCM is the smallest multiple that two or more numbers share.

Step-by-Step Explanation:

1. Include Required Libraries:
We start by including the necessary libraries. In this case, we need the `iostream` library for input and output operations.
C++
``````   #include <iostream>
using namespace std;``````
1. Define a Function to Find LCM:
Next, we define a function that calculates the LCM of two numbers. This function will be later used to calculate the LCM of array elements.
C++
``````   int findLCM(int a, int b) {
int max = (a > b) ? a : b;
while (true) {
if (max % a == 0 && max % b == 0) {
return max;
}
++max;
}
}``````
1. Main Function:
In the main function, we’ll get input from the user – the number of elements in the array and the array itself.
C++
``````   int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;

int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}``````
1. Calculating LCM of Array Elements:
Now, we’ll calculate the LCM of the elements in the array using the `findLCM` function we defined earlier.
C++
``````       int lcm = arr;
for (int i = 1; i < n; ++i) {
lcm = findLCM(lcm, arr[i]);
}``````
1. Displaying the Result:
Finally, we display the calculated LCM to the user.
C++
``````       cout << "LCM of array elements: " << lcm << endl;
return 0;
}``````

Sample Input and Output:

Example Input:

C++
``````Enter the number of elements: 4
Enter the elements: 6 8 12 18``````

Example Output:

C++
``LCM of array elements: 72``

Explanation of the Code:

• The program starts by including the necessary libraries and defining the `findLCM` function.
• In the main function, the user inputs the number of elements in the array and the array itself.
• The program then iterates through the array elements, finding the LCM using the `findLCM` function.
• The calculated LCM is displayed to the user.
• The `findLCM` function calculates the LCM by finding the smallest multiple that’s divisible by both input numbers.
• The main function iterates through the array and calculates the LCM of all elements.

Summary:
This C++ program calculates the LCM of an array of numbers using a user-defined function and a while loop. It provides clear steps for user input, LCM calculation, and output display. The `findLCM` function is essential for calculating the LCM of two numbers. This program is a great example of using functions and loops to solve mathematical problems in programming.

## Examples of Finding the LCM in C++

Let’s look at some examples to see how we can find the LCM in C++. We’ll provide the code, the expected output, and a step-by-step explanation of how this is done.

### Example 1

C++
``````#include<iostream>
using namespace std;
int main() {
int num1 = 6, num2 =

8;
int lcm = (num1 > num2) ? num1 : num2;
while(true) {
if(lcm % num1 == 0 && lcm % num2 == 0) {
cout << "The LCM of " << num1 << " and " << num2 << " is " << lcm;
break;
}
++lcm;
}
return 0;
}``````

Output:

C++
``The LCM of 6 and 8 is 24``

Explanation:

• Purpose: The program calculates the least common multiple (LCM) of two numbers.
• Input: The variables ‘num1’ and ‘num2’ are initialized with the values 6 and 8, respectively.
• Calculation: The program uses a while loop to increment the ‘lcm’ variable and checks if it is divisible by both ‘num1’ and ‘num2’. It continues the loop until it finds the LCM.
• Output: Once the LCM is found, the program prints the result using the ‘cout’ statement.
• Completion: The program exits after executing the code.

### Example 2

C++
``````#include<iostream>
using namespace std;
int main() {
int num1 = 5, num2 = 10;
int lcm = (num1 > num2) ? num1 : num2;
while(true) {
if(lcm % num1 == 0 && lcm % num2 == 0) {
cout << "The LCM of " << num1 << " and " << num2 << " is " << lcm;
break;
}
++lcm;
}
return 0;
}``````

Output:

C++
``The LCM of 5 and 10 is 10``

Explanation:

• Purpose: The program calculates the least common multiple (LCM) of two numbers.
• Input: The variables ‘num1’ and ‘num2’ are initialized with the values 5 and 10, respectively.
• Calculation: The program uses a while loop to increment the ‘lcm’ variable and checks if it is divisible by both ‘num1’ and ‘num2’. It continues the loop until it finds the LCM.
• Output: Once the LCM is found, the program prints the result using the ‘cout’ statement.
• Completion: The program exits after executing the code.

### Example 3

C++
``````#include<iostream>
using namespace std;
int main() {
int num1 = 7, num2 = 9;
int lcm = (num1 > num2) ? num1 : num2;
while(true) {
if(lcm % num1 == 0 && lcm % num2 == 0) {
cout << "The LCM of " << num1 << " and " << num2 << " is " << lcm;
break;
}
++lcm;
}
return 0;
}``````

Output:

C++
``The LCM of 7 and 9 is 63``

Explanation:

• Purpose: The program calculates the least common multiple (LCM) of two numbers.
• Input: The variables ‘num1’ and ‘num2’ are initialized with the values 7 and 9, respectively.
• Calculation: The program uses a while loop to increment the ‘lcm’ variable and checks if it is divisible by both ‘num1’ and ‘num2’. It continues the loop until it finds the LCM.
• Output: Once the LCM is found, the program prints the result using the ‘cout’ statement.
• Completion: The program exits after executing the code.

## Conclusion

In C++, finding the Least Common Multiple (LCM) of two numbers involves identifying the smallest multiple that both numbers can evenly divide into. This process is essential for various mathematical and computational tasks. By using a combination of division, multiplication, and looping structures, we can efficiently compute the LCM. The ‘`findLCM`‘ The function showcased in this program exemplifies this approach, where it iterates through multiples until it identifies the common multiple that satisfies both numbers.

This program demonstrates how abstraction through functions and iterative control structures, like the while loop, simplifies complex mathematical operations. Utilizing these programming concepts not only aids in solving mathematical problems but also enhances code readability, reusability, and maintainability.

## FAQs

• What is the LCM in C++?
The LCM of two numbers is the smallest number that is a multiple of both numbers.
• Why do we need to find the LCM in C++?
We find the LCM in C++ to calculate and manipulate data. It allows our programs to provide useful feedback based on the LCM of two numbers.
• How do we find the LCM in C++?
We find the LCM in C++ by using a while loop and an if statement.
• Can finding the LCM makes the code more confusing?
Yes, if you find the LCM incorrectly, it can lead to confusion and errors. It’s important to understand how to find the LCM and when to use it.
• What are some examples of finding the LCM in C++?
Some examples include calculating the LCM of two numbers and providing the output based on the calculated LCM.