Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
441 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...