Find HCF and LCM of two numbers in C++

In this post we will first understand what is HCF and LCM and then we will write a C++ program to find HCF and LCM of two numbers.

HCF ( Highest Common Factor): The LCM of 2 numbers is Highest common factor of those numbers. For e.g. we have 20 and 30, so HCF will be 10, as 10 is the highest common factor of 20 as well as 30. You must know how to calculate HCF of numbers.

 

LCM ( Lowest Common Multiple): LCM is the lowest common Multiple of those numbers. For e.g. LCM of 5, 7 is 35, as 35 is the least number divisible by both the numbers.

How Code Works:

  1. Take 2 numbers as ‘a’ and ‘b’, and find multiplication of them in ‘c’ i.e. c = a * b.
  2. Now while ‘a’ is not equals to ‘b’ we find the greater and subtract the lower from greater until both become equal.
  3. So finally we will have ‘a’ as our HCF and LCM will be ‘c/a’.

 

Dry run the Code:

  • Let’s take 4 and 6, i.e. a=4 and b=6.
  • Now c=a*b i.e. c=4*6 = 24.
  • While 4 is not equals to 6
  1. 6>4 i.e. b = 6-4 = 2
  2. Now a>b i.e. 4>2 so a = 4-2 =2.
  3. While is over now as ‘a’ = ‘b’
  • HCF = ‘a’ = 2
  • LCM = c / a i.e. 24/2 = 12.

Now let’s see the code.

We can also find the HCF and LCM of Three numbers

C++ Program to find LCM and HCF of two numbers:

# include <iostream>;
using namespace std;

int main()
{
int a,b,c;
cout<< "Enter two nos :"<<endl;
cout<<endl;
cout<< "Enter first no. : ";
cin>>a;
cout<< "Enter sec. no. : ";
cin<<b;
c=a*b;
while(a!=b)
{
    if(a>b)
    a=a-b;
else
    b=b-a;
}
cout<< "HCF = " << a<<endl;
cout<< "LCM = " << c/a<<endl;
return 0;
}

 

OUTPUT:

C++ program to find HCF and LCM

Please comment in case any errors.

3 thoughts on “Find HCF and LCM of two numbers in C++”

Leave a Comment