find the greatest common divisor of two numbers in csharp

Here is a C# function to find the greatest common divisor (GCD) of two integers using the Euclidean algorithm:

main.cs
static int FindGCD(int a, int b)
{
    while (b != 0)
    {
        int remainder = a % b;
        a = b;
        b = remainder;
    }
    return a;
}
151 chars
11 lines

To use this function, you can simply call it and pass in your two numbers:

main.cs
int gcd = FindGCD(12, 18); // gcd is 6
39 chars
2 lines

This function works by repeatedly finding the remainder of a divided by b, and setting a to b and b to the remainder. This continues until b is zero, at which point a represents the GCD of the original two numbers.

gistlibby LogSnag