The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive method Gcd that returns the greatest common divisor of x and y. The Gcd of x and y is defined recursively as follows: If y is equal to 0, then Gcd( x, y ) is x; otherwise, Gcd( x, y ) is Gcd( y, x % y ), where % is the modulus operator.

Could you help me with it (I feel it is very wrong).

214 Views
``````using System;
using System.Collections.Generic;
using System.Text;

namespace exe_2_4
{
class Program
{
static void Main(string[] args)
{
int x, y;
Console.WriteLine("enter the value of x");
Console.WriteLine("enter the value of y");
gcd(x, y);
}
public static void gcd(int x, int y)
{
int z= x%y;
if (y == 0)
Console.WriteLine("the GCD({0},{1}) is {0}", x, y);
else
Console.WriteLine("the GCD({0},{1}) is ({1}, {2})", x,y, z);
}
}
}``````
ddanbe 2,720

Try this:

``````public static int gcd(int x, int y)
{
//First quote from the question:
//"If y is equal to 0, then Gcd( x, y ) is x; "

if (y == 0) return x;

//Second quote:
//"otherwise, Gcd( x, y ) is Gcd( y, x % y ), where % is the modulus operator"

else return gcd(y, x % y);

//so it's seems that you just had to translate your question into code!!!
//but I have to admit, recursion is hard to grasp at first.
}``````

Perhaps you should try the original divised by the greek Euclid :

``````public static int gcd2(int x, int y)
{
while (x != y)
{
if (x > y)
{
x = x - y;
}
else
{
y = y - x;
}
}
return x;
}``````

Remember the modulus operator is really a substraction operator!
have fun!

check this one out:
for more details go to http://www.programmingtunes.com/finding-greatest-common-divisor-of-2-numbers-c/

``````//greatest common divisor of 2 numbers in C++
#include <iostream>
using namespace std;
void main()
{
int x = 24;
int y = 18;
int temp;
for(int i = 2; i<y; i++)
{
if(x%i == 0 && y%i == 0)
{
temp = i;
}

}

cout<<temp<<endl;

}
``````

Hey ... start a new thread please ... did you not see that one was 5 years OLD ?

``````int main() // not void main in standard C
{