Write to calculate GCD / HCF of 2 number
(i) with recursion
(ii) without recursion
#include<iostream>
using namespace std;
int HCF(int x, int y)
{
int tmp;
if(x<y)
{
tmp=x;
x=y;
y=tmp;//using tmp to swap x and y
}
while(x%y!=0)
{
tmp=x%y; //using tmp to store remainder
y=x;
x=tmp;
}
return(y);
}
int HCF_rec(int x, int y){
if(x%y==0)
{
return(y);
}
else
{
HCF(y,x%y);
}
}
void main()
{
int a,b,k;
cout<<"\n Enter Two Numbers: ";
cin>>a>>b;
k=HCF(a,b);
cout<<"\n\n Without Recursion";
cout<<"\n\n HCF ("<<a<<","<<b<<") = "<<k<<"\n\n";
k=HCF_rec(a,b);
cout<<"\n\n Using Recursion";
cout<<"\n\n HCF ("<<a<<","<<b<<") = "<<k<<"\n\n";
system("pause");
}
Comments
Post a Comment