# How to Find the Greatest Common Divisor Using C#

The topic of today’s tutorial will be how to use C# to find the greatest common divisor or GCD. Let’s first have a look at what the GCD is.

## Find the Greatest Common Divisor Using `C#`

The greatest common divisor of two or more non-zero integers is the most significant positive integer that divides the numbers without producing a remainder. It is also known as the greatest common factor (GCF) or highest common factor (HCF).

Let’s use an example to find the greatest common divisor in C#.

• ##### Firstly, we’ll import the following libraries:
``````using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
``````
• ##### In this function, we’ll create a remainder variable `r`, value one called `val1`, and value two named `val2`. This function will find the most divisible integer, as shown below:
``````static int gcdFinder(int val1, int val2) {
int r;
while (val2 != 0) {
r = val1 % val2;
val1 = val2;
val2 = r;
}
return val1;
}
``````
• ##### Then, we’ll get input from the user and parse it to int:
``````int s, h;
``````
• ##### Lastly, we’ll print the results by passing parameters to the `gcdFinder()` function:
``````Console.WriteLine("\n GCD of {0} , {1} is {2}", s, h, gcdFinder(s, h));
``````

Complete Source Code:

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

public class ExamplebyShani {
static int gcdFinder(int val1, int val2) {
int r;
while (val2 != 0) {
r = val1 % val2;
val1 = val2;
val2 = r;
}
return val1;
}

static int Main(string[] args) {
int s, h;
Console.WriteLine("\n GCD of {0}, {1} is {2}", s, h, gcdFinder(s, h));
return 0;
}
}
``````

Output:

``````Please Enter 1st Number: 2