c-sharp
  1. c-sharp-program-to-find-gcd-of-two-numbers

Program to Find GCD of two Numbers - (C# Basic Programs)

In mathematics, GCD (Greatest Common Divisor) is the largest positive integer that divides two or more numbers without leaving a remainder. In this tutorial, we'll discuss a C# program to find the GCD of two numbers using the Euclidean algorithm.

Syntax

The syntax for finding the GCD of two numbers using the Euclidean algorithm in C# is as follows:

int FindGCD(int number1, int number2)
{
    if (number2 == 0)
    {
        return number1;
    }
    else
    {
        return FindGCD(number2, number1 % number2);
    }
}

Example

using System;

namespace GCDExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int number1, number2, gcd;
            Console.Write("Enter first number: ");
            number1 = int.Parse(Console.ReadLine());
            Console.Write("Enter second number: ");
            number2 = int.Parse(Console.ReadLine());
            gcd = FindGCD(number1, number2);
            Console.WriteLine("The GCD of {0} and {1} is {2}.", number1, number2, gcd);
            Console.ReadLine();
        }

        static int FindGCD(int number1, int number2)
        {
            if (number2 == 0)
            {
                return number1;
            }
            else
            {
                return FindGCD(number2, number1 % number2);
            }
        }
    }
}

Output:

Enter first number: 24
Enter second number: 36
The GCD of 24 and 36 is 12.

Explanation

The Euclidean algorithm is an efficient method of finding the GCD of two numbers. It works by repeatedly subtracting the smaller number from the larger number until both numbers become equal, and then returning that number as the GCD. The C# program uses a recursive function to implement the Euclidean algorithm to find the GCD of two numbers.

Use

A program to find the GCD of two numbers is useful in mathematical applications where finding the largest common divisor between two or more numbers is necessary. It is also a common programming exercise that helps improve problem-solving skills and understanding of recursion in programming.

Summary

In this tutorial, we discussed a C# program to find the GCD of two numbers using the Euclidean algorithm. We covered the syntax, example, explanation, and use of finding the GCD of two numbers in C#. By understanding the Euclidean algorithm and using recursion, programmers can write efficient programs to find the GCD of two numbers.

Published on: