Greatest Common Divisor from a set of more than 2 integers

后端 未结 13 1066
遇见更好的自我
遇见更好的自我 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 04:59

    Without using LINQ.

        static int GCD(int a, int b)
        {
            if (b == 0) return a;
            return GCD(b, a % b);
        }
    
        static int GCD(params int[] numbers)
        {
            int gcd = 0;
            int a = numbers[0];
            for(int i = 1; i < numbers.Length; i++)
            {
                gcd = GCD(a, numbers[i]);
                a = numbers[i];
            }
    
            return gcd;
        }
    

提交回复
热议问题