Recursive Method
You can change your GetGCD()
method to be much more intuitive and minimal using a ternary operator and recursion. I recommend also documenting what it's doing for readability purposes:
static int GetGCD(int x, int y)
{
// If y is equal to 0, return x.
// If y is not equal to 0, recursive call with x as y and y as the remainder.
return y == 0 ? x : GetGCD(y, x % y);
}
Can also be written as:
static int GetGCD(int x, int y)
{
// If y is equal to 0, return x.
if (y == 0)
return x;
// If y is not equal to 0, recursive call with x as y and y as the remainder.
return GetGCD(y, x % y);
}
Depending on your preference.
Iterative Method
As stated in other answers, you might use an iterative method:
static int GetGCD(int x, int y)
{
while (y != 0)
{
int tmp = x % y;
x = y;
y = tmp;
}
return x;
}
Entry Point
Use TryParse()
for retrieving integer input from the console. We don't want exceptions on user input.
Modular arithmetic should be positive. To ensure this, we use the absolute value of the input (Euclidean division). Here's how I would implement it:
static void Main()
{
int x, y;
// Get x. Ensure it's an integer.
Console.WriteLine("Input first number: ");
while(!Int32.TryParse(Console.ReadLine(), out x));
// Get y. Ensure it's an integer.
Console.WriteLine("Input second number: ");
while(!Int32.TryParse(Console.ReadLine(), out y));
// Ensure the values being used are positive.
Console.WriteLine(GetGCD(Math.Abs(x), Math.Abs(y)));
Console.ReadKey();
}
Output
As you can see, it will wait for an input that can be parsed to an integer and returns the expected value:
Input first number:
a
b
c
585
Input second number:
d
442
13
Benchmark
Just for fun, I thought I'd test the difference between the recursive and iterative methods.
Benchmarked method: Recursive
Test cases: 20
Bench in MS: 184
Iterations per case: 10000000
Benchmarked method: Iterative
Test cases: 20
Bench in MS: 121
Iterations per case: 10000000
The difference is negligible in real application (unless you plan to run this millions of times). These tests were run from entirely different processes.