Q:

C# program to find the greatest common divisor (GCD)

0

C# program to find the greatest common divisor (GCD)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to find the Greatest Common Divisor is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to find the greatest common divisor (GCD) 

using System;

class GcdClass
{
    static void Main(string[] args)
    {
        int num1 = 0;
        int num2 = 0;
        int GCD  = 0;

        GcdClass G = new GcdClass(); ;

        Console.Write("Enter the 1st Number : ");
        num1 = Convert.ToInt32(Console.ReadLine());
        
        Console.Write("Enter the 2nd Number : ");
        num2 = Convert.ToInt32(Console.ReadLine());

        GCD = G.GetGcd(num1, num2);

        Console.WriteLine("\nThe Greatest Common Divisor is: "+GCD);
    }

    int GetGcd(int number1, int number2)
    {
        int rem = 0;

        while (number2 > 0)
        {
            rem = number1 % number2;
            number1 = number2;
            number2 = rem;
        }
        return number1;
    }
}

Output:

Enter the 1st Number : 8
Enter the 2nd Number : 12

The Greatest Common Divisor is: 4
Press any key to continue . . .

Explanation:

Here, we created a class GcdClass that contain an instance method GetGcd() and a static method Main().

In the GetGCD() method, we passed two numbers, and find the Greatest Common Divisor of two numbers, then return the GCD to the calling method.

The GCD of two numbers is the highest positive number that can divide both numbers without any remainder.

Coming to the Main() method, In the Main() method, we read the values of two integer numbers and then find the GCD using GetGcd() method and the print the GCD on the console screen.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now