Greatest Common Divisor from a set of more than 2 integers
Solution 1:
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);
}
Solution 2:
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);
}
}
Solution 3:
Wikipedia:
The gcd is an associative function: gcd(a, gcd(b, c)) = gcd(gcd(a, b), c).
The gcd of three numbers can be computed as gcd(a, b, c) = gcd(gcd(a, b), c), or in some different way by applying commutativity and associativity. This can be extended to any number of numbers.
Just take the gcd of the first two elements, then calculate the gcd of the result and the third element, then calculate the gcd of the result and fourth element...