((((((Don't copy and paste it. Please Practice These programs are provided to create interest in Students))))))))
#include<iostream> //This is actual program executed in gcc compilers like Putty
#include<stdlib.h> //similar to previous factorial program with switch case without labels
using namespace std;
int gcdr(int,int); //Recursive method
int gcdnr(int,int); //Non-Recursive method
int main()
{
int m,n,gcd;
char ch;
cout<<"enter 'm', 'n' value to find Greatest Common Divisor :: ";
cin>>m>>n;
while(n<0||m<0) //Validating m, n values for GCD
{
cout<<"Please enter valid(only positive) m, n values"<<endl;
cin>>m>>n;
}
if(m==0&&n==0)
{
cout<<"GCD not possible. \n terminating program"<<endl;
exit(0);
}
cout<<"\nenter 'r' to implement Recursive method"<<endl;
cout<<"\nenter 'n' to implement Non-Recursive method"<<endl;
cin>>ch ;
switch(ch)
{
case 'r':
gcd=gcdr(m,n);
cout<<"Executing Recursive Method"<<endl;
cout<<"\nGCD of "<<m<<","<<n<<" is: "<<gcd;
break;
case 'n':
gcd=gcdnr(m,n);
cout<<"\nGCD of "<<m<<","<<n<<" is: "<<gcd;
break;
default:
cout<<"Invalid choice"<<endl;
cout<<"Terminating the program"<<end;
}
return 0;
}
int gcdnr(int m,int n)
{
int r;
cout<<"Executing Non-Recursive Method"<<endl;
if(m==0||n==0) //GCD of Any +ve number with 0 is itself the number
{
return m+n;
}
while(n|=0)
{
r=m%n; //logic for GCD is divide greater no: by smaller and save remainder
//divide the smaller value by the above remainder value
//repeat this process until successful division (one divides another)
m=n;
n=r;
}
return m;
}
int gcdr(int m,int n)
{
if(n==0)
return m;
if(m==0||n==0)
{ return m+n;
}
else
return gcdr(n,m%n);
}
No comments:
Post a Comment