There are several questions on Stack Overflow discussing how to find the Greatest Common Divisor of two values. One good answer shows a neat recursive function
Without using LINQ.
static int GCD(int a, int b)
{
if (b == 0) return a;
return GCD(b, a % b);
}
static int GCD(params int[] numbers)
{
int gcd = 0;
int a = numbers[0];
for(int i = 1; i < numbers.Length; i++)
{
gcd = GCD(a, numbers[i]);
a = numbers[i];
}
return gcd;
}
And here you have code example using LINQ and GCD method from question you linked. It is using theoretical algorithm described in other answers ... GCD(a, b, c) = GCD(GCD(a, b), c)
static int GCD(int[] numbers)
{
return numbers.Aggregate(GCD);
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
By using this, you can pass multiple values as well in the form of array:-
// pass all the values in array and call findGCD function
int findGCD(int arr[], int n)
{
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = getGcd(arr[i], gcd);
}
return gcd;
}
// check for gcd
int getGcd(int x, int y)
{
if (x == 0)
return y;
return gcd(y % x, x);
}
You could use this common property of a GCD:
GCD(a, b, c) = GCD(a, GCD(b, c)) = GCD(GCD(a, b), c) = GCD(GCD(a, c), b)
Assuming you have GCD(a, b)
already defined it is easy to generalize:
public class Program
{
static void Main()
{
Console.WriteLine(GCD(new[] { 10, 15, 30, 45 }));
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
static int GCD(int[] integerSet)
{
return integerSet.Aggregate(GCD);
}
}
GCD(a, b, c) = GCD(a, GCD(b, c)) = GCD(GCD(a, b), c) = GCD(GCD(a, c), b)
enter code here
public class Program { static void Main() { Console.WriteLine(GCD(new[] { 10, 15, 30, 45 })); } static int GCD(int a, int b) { return b == 0 ? a : GCD(b, a % b); } static int GCD(int[] integerSet) { return integerSet.Aggregate(GCD); } }
Rewriting this as a single function...
static int GCD(params int[] numbers)
{
Func<int, int, int> gcd = null;
gcd = (a, b) => (b == 0 ? a : gcd(b, a % b));
return numbers.Aggregate(gcd);
}