Question -
Given two number, you have to find the hcf and lcm of the numbers.
Example -
Input: a = 2 , b = 3
Output : Hcf = 1 , Lcm = 6
Approach -
We calculate hcf first and then calculate lcm with the help of hcf.
Implementation -
//To find the lcm and hcf of two numbers
#include<iostream>
using namespace std;
int hcfmethod1(int a,int b)
{
if(a==0)
return b;
else
while(b){
if(a>b)
a=a-b;
else
b=b-a;
}
return a;
}
int hcfmethod2(int a,int b)
{
if(a==0)
return b;
else
while(b){
if(a>b)
a=a-b;
else
b=b-a;
}
return a;
}
int main()
{
int a,b;
cout<<"Enter two numbers : "<<endl;
cin>>a;
cin>>b;
int hcf=hcfmethod1(a,b);//use mehtod1 or method2
int lcm=(a*b)/hcf;
cout<<"Lcm : "<<lcm<<endl<<"Hcf : "<<hcf<<endl;
return 0;
}
Comments
Post a Comment