find the greatest common divisor of a list of numbers in csharp

Here's a method to find the greatest common divisor of a list of integers in C# using Euclid's algorithm:

main.cs
public static int GetGCD(List<int> nums)
{
    if (nums == null || nums.Count == 0)
        throw new ArgumentException("List cannot be null or empty.");

    int result = nums[0];
    for (int i = 1; i < nums.Count; i++)
    {
        result = GetGCD(result, nums[i]); 
        // uses overload below to get gcd of two numbers
    }
    return result;
}

private static int GetGCD(int a, int b)
{
    if (b == 0)
        return a;
    else
        return GetGCD(b, a % b);
}
476 chars
22 lines

The GetGCD method takes a list of integers as input and iterates through the list, calling the GetGCD method on the current element and the result so far. The GetGCD(int a, int b) method uses Euclid's algorithm to recursively find the greatest common divisor of two numbers.

related categories

gistlibby LogSnag