Pages

Saturday, June 29, 2013

Recursive function to find greatest common divisor

/*
QUESTION:

Write a recursive function that will find the greatest common divisor of two inputs. Basically the greatest common divisor of two integers x and y is generally the largest number that evenly divides both numbers.

*/

CODE:

#include <iostream>
using namespace std;

int gcd(int x, int y);
//MAIN STARTS
int main(){
 int a,b;
cout<<"ENTER FIRST NUMBER : ";
cin>>a;

cout<<"\nENTER SECOND NUMBER : ";
cin>>b;

cout<<"\n\n THE GREATEST COMMON DIVISOR IS : "<<gcd(a,b)<<endl;

 return 0;
}

//MAIN ENDS
int gcd(int x, int y){
if (x==0)
return y;
if(y==0)
return x;
if (x == y)
return y;

else
return gcd(y,x%y);


}




 

No comments:

Post a Comment