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:
- Take 2 numbers as ‘a’ and ‘b’, and find multiplication of them in ‘c’ i.e. c = a * b.
- Now while ‘a’ is not equals to ‘b’ we find the greater and subtract the lower from greater until both become equal.
- 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
- 6>4 i.e. b = 6-4 = 2
- Now a>b i.e. 4>2 so a = 4-2 =2.
- 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 HCF and LCM of two numbers
[code lang=”cpp”]# include <iostream>;
using namespace std;
cout<< "Enter two nos :"<<endl;
cout<< "Enter first no. : ";
cout<< "Enter sec. no. : ";
cout<< "HCF = " << a<<endl;
cout<< "LCM = " << c/a<<endl;
Please comment in case any errors.