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

Here, we are going to learn how to find the greatest common divisor (GCD) in C#?
Submitted by Nidhi, on September 21, 2020

Here, we will find the Greatest Common Divisor of two numbers. The GCD is the highest positive number that can divide both numbers without any remainder.

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.