Home »
.Net »
C# Programs
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#?
By Nidhi Last updated : April 15, 2023
Greatest Common Divisor of Two Numbers
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.
C# code to find the greatest common divisor of two numbers
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.
C# Basic Programs »