Reputation: 55
I am on the newer side of using c# for coding. I am looking to find the greatest common denominator of two inputted values. There are some numbers that work, such as 100 &200, 50&150, 2&12, etc. But when I put in 78 with anything but itself I keep getting stack overflow message.
I have attached my code below.
Can someone tell me why I might be getting this message?
using System;
namespace Euclid_App
{
class Euclidbackground
{
public static long GreatestCommoner(long first, long second)
{
while (first != second)
{
if (first > second)
{
return GreatestCommoner(first - first , second);
}
else
{
return GreatestCommoner(first, second - first);
}
}
return first;
}
}
class Program
{
static void Main(string[] args)
{
long onenum;
long twonum;
Console.WriteLine("Type first number:");
onenum = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Type second number:");
twonum = Convert.ToInt64(Console.ReadLine());
long answer = Euclidbackground.GreatestCommoner(onenum, twonum);
Console.WriteLine(answer);
Console.ReadKey();
}
}
}
Upvotes: 0
Views: 54
Reputation: 13456
Here's a typo:
//this is always 0
return GreatestCommoner(first - first , second);
Replace this line with:
return GreatestCommoner(first - second, second);
By the way, this while loop is unnecessary, since it will have only one iteration you should probably replace it with an if statement.
P.S. You might want to add some validation for your input parameters. Something like this:
Debug.Assert(first>0);
Debug.Assert(second>0);
will protect you from many issues with invalid calls.
P.P.S. Also, practice your debugging skills. Something as straightforward as:
Console.WriteLine(first+" "+second);
will help you understand the problem better. If you have an IDE you should be able to use more convenient debugging tools.
Upvotes: 2