Software & Finance - Monthly Magazine Online

Volume 4 - Issue 2

February 2014

Find GCD and LCM for two numbers with simple program


I have given here the C# source code for calculating Greatest Common Divisor(GCD) and Least Common Multiple (LCM).

 

GCD can be found with a simple while loop by comaring the two numbers and assigning the difference to the largest number until the two numbers are equal. Once you know GCD, finding LCM is easy with the formula 

LCM(a,b) = (a * b)/ GCD(a,b)

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication1

{

    class Program

    {

        static int GetGCD(int num1, int num2)

        {

            while (num1 != num2)

            {

                if (num1 > num2)

                    num1 = num1 - num2;

 

                if (num2 > num1)

                    num2 = num2 - num1;

            }

            return num1;

        }

 

 

        static int GetLCM(int num1, int num2)

        {

            return (num1 * num2) / GetGCD(num1, num2);

        }

 

        static void Main(string[] args)

        {

            Console.WriteLine("C# Program for LCM and GCD");

 

            Console.Write("Enter First Number: ");

            int a = Convert.ToInt32(Console.ReadLine());

 

            Console.Write("Enter Second Number: ");

            int b = Convert.ToInt32(Console.ReadLine());

 

            int gcd = GetGCD(a, b);

            int lcm = GetLCM(a, b);

 

            Console.WriteLine("\nGCD({0,4},{1,4}) = {2,6}", a, b, gcd);

            Console.WriteLine("\nLCM({0,4},{1,4}) = {2,6}", a, b, lcm);

 

        }

    }

}

 

Output


 

C# Program for LCM and GCD

Enter First Number: 10

Enter Second Number: 135

 

GCD(10,135) = 5

LCM(10,135) = 270

 

 

Press any key to continue . . .