Saturday, June 11, 2016

Write a program to find GCD of 2 numbers in C#.NET



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

namespace ConsoleApplication17
{
    class Program
    {
        static void Main()
        {
            int i, i1;

            Console.WriteLine("Enter 2 numbers to find GCD");
            i = int.Parse(Console.ReadLine());
            i1 = int.Parse(Console.ReadLine());

            int num, num1;
      
            if (i > i1)
            {
                num = i;
                num1 = i1;
            }
            else
            {
                num = i1;
                num1 = i;
            }
            int output = gcd(num, num1);
            Console.WriteLine("The GCD of {0} and {1} is {2}", i, i1, output);
            Console.Read();
        }

        private static int gcd(int num, int num1)
        {
            int rem = 5;
            while (num1 > 0)
            {
                rem = num % num1;
                if (rem == 0)
                    return num1;
                num = num1;
                num1 = rem;

            }

            return num;

        }
    }
}

Output : 



No comments:

Post a Comment