GCD
Calculates the greatest common divisor of the given numbers.
- Define a
GCD()function for two numbers, which uses recursion. - Base case is when
yequals0, which returnsx. - Otherwise the GCD of
yand the remainder of the divisionx/yis returned. - Define an overload that accepts multiple numbers or an array and use
IEnumerable.Aggregate()to applyGCD()to them.
using System.Linq;
public static partial class _30s
{
public static int GCD(params int[] nums)
{
return nums.Aggregate(GCD);
}
public static int GCD(int x, int y)
{
return y == 0 ? x : GCD(y, x % y);
}
}_30s.GCD(8, 36, 28); // 4