find the least common multiple of two numbers in csharp

To find the least common multiple of two numbers in C#, we can use the following algorithm:

  1. Find the greatest common divisor (GCD) of the two numbers by using the Euclidean algorithm.
  2. Multiply the two numbers together.
  3. Divide the product of the two numbers by the GCD.

Here is the C# code for finding the LCM of two numbers:

main.cs
using System;

public class Program
{
    public static void Main()
    {
        int num1 = 24;
        int num2 = 36;

        int lcm = GetLCM(num1, num2);

        Console.WriteLine($"LCM of {num1} and {num2} is {lcm}");
    }

    private static int GetLCM(int num1, int num2)
    {
        int gcd = GetGCD(num1, num2);
        return (num1 * num2) / gcd;
    }

    private static int GetGCD(int num1, int num2)
    {
        while (num2 != 0)
        {
            int temp = num2;
            num2 = num1 % num2;
            num1 = temp;
        }

        return num1;
    }
}
587 chars
33 lines

In this example, we have two numbers (24 and 36) for which we want to find the LCM. We use the GetLCM method to calculate the LCM and the GetGCD method to calculate the GCD. The GetGCD method uses the Euclidean algorithm to find the GCD.

The output of the program is:

main.cs
LCM of 24 and 36 is 72
23 chars
2 lines

which is the correct LCM of 24 and 36.

gistlibby LogSnag