I'm trying to find GRC for N numbers. For example N = 4, so the 4 numbers is for example 199 199 -199 -199. And im getting StackOverflowException for those numbers. Why? first input number of integers for which i should find GRC. Second input number is array of numbers wroted in one line separeted by " ". Here is my code:
static int GCD(int a, int b)
{
if (b == 0) return a;
if (a > b) return GCD(b, a - b);
else return GCD(a, b-a);
}
static void Main()
{
var input = Convert.ToInt32(Console.ReadLine());
int gcd;
string readLine = Console.ReadLine();
string[] stringArray = readLine.Split(' ');
int[] intArray = new int[input];
for (int i = 0; i < stringArray.Length; i++)
{
intArray[i] = int.Parse(stringArray[i]);
}
if (input >= 2)
{
gcd= Math.Abs(GCD(intArray[0], intArray[1]));
}
else
{
gcd= intArray[0];
}
for (int i = 2; i < input; i++)
{
gcd= Math.Abs(GCD(gcd, intArray[i]));
}
Console.WriteLine(Math.Abs(gcd));
Console.ReadKey();
}
Any suggestions how to improve the code?
First of all, it's unclear what is
GRC
. Your code is aboutGCD
- Greatest Common Divisor. Let's improve its implementation.If you have huge difference, beween
a
andb
, saya = 1_000_000_000
andb = 1
you are going to have~ a - b ~ 1_000_000_000
recursive calls inGCD
and have Stack Overflow Exception.Let's use modulo arithmetics instead: if
a = b + b + ... + b + remainder
, we can find remainder in one go, without subtractingb
:remainder = a % b
Code:
then we can compute
GCD
for as many numbers as we wantUsage: (fiddle)