Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greatest Common Divisor from a set of more than 2 integers

Tags:

c#

algorithm

math

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?
}
like image 339
BG100 Avatar asked Sep 03 '10 12:09

BG100


People also ask

How do you find the GCD of two or more integers?

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).

How do you find the GCD of 5 numbers?

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.

What do we call the largest common divisor of two or more numbers?

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.


1 Answers

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);
}
like image 184
Martin Jonáš Avatar answered Oct 23 '22 11:10

Martin Jonáš