find the least common denominator from a list of longs in csharp

To find the Least Common Denominator (LCD) from a list of longs in C#, we can make use of the property that the LCD of a set of numbers is the smallest multiple of these numbers.

Here's one way to implement this:

main.cs
using System;

public class Program
{
    public static void Main(string[] args)
    {
        long[] numbers = { 12, 18, 24, 36 };
        
        long lcd = numbers[0];
        for (int i = 1; i < numbers.Length; i++)
        {
            lcd = LCM(lcd, numbers[i]);
        }
        
        Console.WriteLine("Least Common Denominator: " + lcd);
    }
    
    // Helper function to find the gcd of two numbers
    private static long GCD(long a, long b)
    {
        while (b != 0)
        {
            long temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    
    // Function to find the lcm of two numbers using the gcd
    private static long LCM(long a, long b)
    {
        return (a * b) / GCD(a, b);
    }
}
767 chars
36 lines

Here, we initialize the LCD to be the first number in the list, and then loop through the rest of the numbers, calling the LCM function to find the LCD of the current number and the previously computed LCD.

The LCM function uses the GCD (Greatest Common Divisor) function to compute the LCM using the formula (a * b) / gcd(a, b).

We can then print out the final value of the LCD.

gistlibby LogSnag