﻿ C++ Exercises: Find LCM of any two numbers using HCF - w3resource

# C++ Exercises: Find LCM of any two numbers using HCF

## C++ For Loop: Exercise-29 with Solution

Write a program in C++ to find the LCM of any two numbers using HCF.

Visual Presentation:

Sample Solution:-

C++ Code :

``````#include <iostream> // Including input-output stream header

using namespace std; // Using standard namespace to avoid writing std::

int main() // Start of the main function
{
int i, n1, n2, j, hcf = 1, lcm; // Declaration of integer variables: 'i' (loop counter), 'n1' and 'n2' (input numbers), 'j' (temporary variable), 'hcf' (stores the HCF), 'lcm' (stores the LCM)

cout << "\n\n LCM of two numbers:\n"; // Displaying a message on the console
cout << "------------------------\n";
cout << " Input 1st number for LCM: "; // Asking the user for the 1st number
cin >> n1; // Reading the 1st number from the user
cout << " Input 2nd number for LCM: "; // Asking the user for the 2nd number
cin >> n2; // Reading the 2nd number from the user

j = (n1 < n2) ? n1 : n2; // Determining the smaller of the two numbers

for (i = 1; i <= j; i++) { // Loop to find the Highest Common Factor (HCF)
if (n1 % i == 0 && n2 % i == 0) { // Checking if 'i' is a common factor of both numbers
hcf = i; // Updating the HCF when 'i' is a common factor
}
}

/* mltiplication of HCF and LCM = the multiplication of these two numbers.*/
lcm = (n1 * n2) / hcf; // Calculating the Least Common Multiple (LCM) using the formula LCM * HCF = Product of the numbers

cout << " The LCM of " << n1 << " and " << n2 << " is: " << lcm << endl; // Displaying the calculated LCM
}
``````

Sample Output:

``` LCM of two numbers:
------------------------
Input 1st number for LCM: 15
Input 2nd number for LCM: 25
The LCM of 15 and 25 is: 75
```

Flowchart:

C++ Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

﻿