Greatest Common Divisor from a set of more than 2 integers

后端 未结 13 1018
遇见更好的自我
遇见更好的自我 2020-12-09 04:25

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

13条回答
  •  自闭症患者
    2020-12-09 05:01

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

提交回复
热议问题