Sponsored Ad

Tuesday, September 14, 2010

C# Program to calculate LCM (Least common multiple)

The least common multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both. So first you need to find out the minimum factors of a number and then calculate the LCM by multiplying factors.

C# Program to calculate LCM (Least common multiple)

Code for LCM:

using System;
using System.Text;
using System.Collections;
using System.Data;
namespace Console_App
{
    public class clsLCM
    {
        public static void Main()
        {
            try
            {
                int n, i, j, c = 0, maxNumber, minNumber;
                int[] Numbers = new int[20];
                long prod;
                Console.WriteLine("Enter the no. of entries: ");
                n = Convert.ToInt16(Console.ReadLine());

                Console.WriteLine("Enter the entries: ");

                for (i = 0; i < n; i++)
                {
                    c = Convert.ToInt16(Console.ReadLine());

                    if (c > 0)
                        Numbers[i] = c;
                    else
                    {
                        Console.WriteLine("Invalid Entry ");
                        return;
                    }
                }

                maxNumber = Numbers[0];
                for (i = 0; i < n; i++)
                    if (Numbers[i] >= maxNumber)
                        maxNumber = Numbers[i];
                minNumber = Numbers[0];
                for (i = 0; i < n; i++)
                    if (Numbers[i] < minNumber)
                        minNumber = Numbers[i];

                for (i = 0, prod = 1; i < n; i++)
                    prod = prod * Numbers[i];

                for (i = maxNumber; i <= prod; i += maxNumber)
                {

                    c = 0;
                    for (j = 0; j < n; j++)
                        if (i % Numbers[j] == 0)
                            c += 1;
                    if (c == n)
                    {
                        Console.WriteLine("The LCM of the nos: {0} ", i);

                        break;
                    }
                }

            }
            catch (Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();
        }
    }
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers