C# find the greatest common divisor

后端 未结 9 1545
夕颜
夕颜 2020-12-02 23:11

\"The greatest common divisor of two integers is the largest integer that evenly divides each of the two numbers. Write method Gcd that returns the greatest common divisor o

9条回答
  •  旧时难觅i
    2020-12-02 23:35

    Using LINQ's Aggregate method:

    static int GCD(int[] numbers)
    {
        return numbers.Aggregate(GCD);
    }
    
    static int GCD(int a, int b)
    {
        return b == 0 ? a : GCD(b, a % b);
    }
    

    Note: answer above borrowed from accepted answer to Greatest Common Divisor from a set of more than 2 integers.

提交回复
热议问题