c-sharp
  1. c-sharp-program-to-find-lcm-of-two-numbers

Program to Find LCM of two Numbers - (C# Basic Programs)

Finding the least common multiple (LCM) of two numbers is a common programming problem that helps improve problem-solving skills. In this tutorial, we will discuss a program to find the LCM of two numbers using C# programming language.

Syntax

The syntax for finding the LCM of two numbers in C# is as follows:

public static int LCM(int num1, int num2) {
    int max = Math.Max(num1, num2);
    int min = Math.Min(num1, num2);
    int lcm = max;
    while (lcm % min != 0) {
        lcm += max;
    }
    return lcm;
}

Example

using System;

class Program {
    static void Main(string[] args) {
        Console.Write("Enter first number: ");
        int num1 = int.Parse(Console.ReadLine());
        Console.Write("Enter second number: ");
        int num2 = int.Parse(Console.ReadLine());
        int lcm = LCM(num1, num2);
        Console.WriteLine("LCM of {0} and {1} is {2}", num1, num2, lcm);
    }

    public static int LCM(int num1, int num2) {
        int max = Math.Max(num1, num2);
        int min = Math.Min(num1, num2);
        int lcm = max;
        while (lcm % min != 0) {
            lcm += max;
        }
        return lcm;
    }
}

Output:

Enter first number: 6
Enter second number: 8
LCM of 6 and 8 is 24

Explanation

To find the LCM of two numbers, we take the larger of the two numbers and begin multiplying it by successively larger multiples of the other number until we find a multiple that is common to both numbers. In the given C# program, we have used the While loop to calculate LCM by finding the multiple of the largest number that is also a multiple of the small number.

Use

Finding the LCM of two numbers is an important task when working with mathematical computations. This program can be used in any C# application that requires the LCM of two numbers to be calculated.

Summary

In this tutorial, we discussed a program in C# to find the LCM of two numbers. We have seen the syntax, example, explanation, and use of calculating the LCM of two numbers using the C# programming language. By practicing and understanding these programming exercises, programmers can improve their problem-solving skills and become better equipped to tackle complex mathematical problems in their programs.

Published on: