find the least common multiple of a list of numbers in csharp

To find the least common multiple (LCM) of a list of numbers in C#, we can use the fact that LCM(a, b, c) = LCM(a, LCM(b, c)). In other words, we can reduce the problem to finding the LCM of two numbers at a time. Here's one way to implement this algorithm:

main.cs
using System;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        List<int> numbers = new List<int> {2, 3, 4, 5};
        int lcm = LCM(numbers);
        Console.WriteLine("LCM: " + lcm); // Output: LCM: 60
    }

    public static int LCM(List<int> numbers) {
        int lcm = numbers[0];
        for (int i = 1; i < numbers.Count; i++) {
            lcm = LCM(lcm, numbers[i]);
        }
        return lcm;
    }

    public static int LCM(int a, int b) {
        return a * b / GCD(a, b);
    }

    public static int GCD(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
}
721 chars
32 lines

The LCM method takes a list of integers, loops through it, and calculates the LCM of each pair of numbers using the LCM helper method. The LCM method takes two integers and calculates their LCM using the formula a * b / GCD(a, b). Finally, the GCD method calculates the greatest common divisor of two numbers using the Euclidean algorithm.

We can test the implementation by passing in the list {2, 3, 4, 5}. The LCM should be 60.

related categories

gistlibby LogSnag