Friday 24 April 2015

How to find LCM of two number in c# asp.net ?

Concept:-


The least common multiple (LCM) of two numbers is the smallest number that is a multiple of both.
Blow I written a c# program it will ask to enter two number then will find the LCM of both and print it.

Source code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp
{
    class Program
    {
        public static void Main(String[] args)
        {
            int n1, n2;

            Console.WriteLine("Enter the first number");
            n1 = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter the second number");
            n2 = int.Parse(Console.ReadLine());

            int result = determineLCM(n1, n2);

            Console.WriteLine("LCM of {0} and {1} is {2}", n1, n2, result);
            Console.Read();
        }
        public static int determineLCM(int a, int b)
        {
            int num1, num2;
            if (a > b)
            {
                num1 = a; num2 = b;
            }
            else
            {
                num1 = b; num2 = a;
            }

            for (int i = 1; i <= num2; i++)
            {
                if ((num1 * i) % num2 == 0)
                {
                    return i * num1;
                }
            }
            return num2;
        }

    }

}

Output:-


No comments:

Post a Comment