WAP to calculate GCD of two numbers (i) with recursion (ii) without recursion.





#include<iostream.h>
#include<conio.h>
class gcd
{
int m,n;
public:
gcd();
void gcditeration();
int gcdrecursion(int m,int n);
};
gcd::gcd()
{
cout<<"enter the value of n"<<endl;
cin>>n;
cout<<"enter the value of m"<<endl;
cin>>m;
}
void gcd::gcditeration()
{
  int max=(m>n)?m:n;
   max=(n>m)?n:m;
  int min=(m>n)?n:m;
  min=(n>m)?m:n;
  for(int i=min;i>=1;i--)
  {
  if((min%i==0) && (max%i==0))
  {
  cout<<"the gcd by iteration is "<<i<<endl;
  break;
  }
  }
  cout<<"gcd using recursion is "<<gcdrecursion(max,min)<<endl;
}
int gcd::gcdrecursion(int n,int m)
{
if(n%m==0)
return(m);
else
return(gcdrecursion(n,n%m));
}


 void main()
 {
 clrscr();
 gcd obj;
 obj.gcditeration();
 getch();
 }

Output:- 


Comments

Post a Comment