Sponsored Ad

Tuesday, September 14, 2010

How to Find GCD (Greatest Common Divisor) of Numbers using C#

To find greatest common divisor you need to first find the prime factors of given numbers. like for 5 and 10. the prime factors are:

5 =  5, 1

10 = 5, 2, 1

now find the common prime factors and multiply them.

5 x 1 = 5 , so GCD is 5. The C# Program is given below to calculate GCD .

 

How to Find GCM (Greatest Common Divisor) of Numbers using C#

Code of GCD:

using System;
using System.Text;
using System.Collections;
using System.Data;
namespace Console_App
{
    public class clsGCD
    {
        public static void Main()
        {
            try
            {
                int n, i, j, c = 0,  minNumber;
                int[] Numbers = new int[20];
                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;
                    }
                }

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

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

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

1 comments:

  1. This is the recursive version using Euclid's algorithm.

    int GCD(int m, int n) {
    if (n == 0) return m;
    return GCD(n, m % n);
    }

    ReplyDelete

Sponsored Ad

Website Update

Followers