In this example, you will learn a c++ program to find LCM and HCF.
LCM means the least common multiple. If we have two numbers 6 and 10, The LCM of these numbers will be 30. It means that 6 and 10 are the least common multiple of 30.
While on the other hand HCF means the highest common factor. If we have two numbers 30 and 25, the HCF of these numbers will be 5. It means that 5 is the highest common factor that is divisible by both 30 and 25.
Example: C++ program to find HCF and LCM
Here is the code to take two numbers from the user. The program finds out HCF and LCM and displays them on the screen.
//C++ program to find HCF and LCM
#include<iostream>
using namespace std;
int main()
{
int x, y, num1, num2, temp, hcf, lcm;
cout<<"Enter First number: ";
cin>>num1;
cout<<"Enter second numbers: ";
cin>>num2;
x=num1;
y=num2;
while(y!=0)
{
temp=y;
y=x%y;
x=temp;
}
hcf=x;
lcm=(num1*num2)/hcf;
cout<<"\n HCF : "<<hcf<<"\n";
cout<<"\n LCM : "<<lcm<<"\n";
return 0;
}
Output
Description and working of this program
- Initialize 7 variables and named them x, y, num1, num2, temp, hcf, lcm
- Take two numbers from the user and store them in num1 and num2.
- Assign num1 and num2 values to x and y.
- Initialize while loop until y is not equal to zero.
- Inside while loop assigns y value to temp variable.
- Calculate modules of x and y by following this formula y=x%y
- After that assign temp value to x.
- Continue while loop until y is not equal to zero.
- When y is equal to zero while loop is terminated.
- After that store the x value to the hcf variable.
- LCM is calculate by the following formula lcm = (num1*num2)/hcf
- Now print both hcf and lcm on the screen.