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 to do this.
But how can I find the GCD of a set of more than 2 integers? I can't seem to find an example of this.
Can anyone suggest the most efficient code to implement this function?
static int GCD(int[] IntegerSet)
{
// what goes here?
}
As per the LCM method, we can obtain the GCD of any two positive integers by finding the product of both the numbers and the least common multiple of both numbers. LCM method to obtain the greatest common divisor is given as GCD (a, b) = (a × b)/ LCM (a, b).
For example, the greatest common factor of 15 and 10 is 5, since both the numbers can be divided by 5. If a and b are two numbers then the greatest common divisor of both the numbers is denoted by gcd(a, b). To find the gcd of numbers, we need to list all the factors of the numbers and find the largest common factor.
The greatest common factor (GCF) of a set of numbers is the largest factor that all the numbers share. For example, 12, 20, and 24 have two common factors: 2 and 4.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With