I’ve decided to create a post series with methods I found useful, especially when solving programming challenges. The first one is how to calculate the Greatest Common Divisor (GCD) of two numbers. GCD is the largest number that divides both numbers without a reminder. We follow the Euclidean algorithm which is very simple and fast. The method is created as static since it is just data in and data out. We use long datatype, it can be easily replaced with int if you need to change it. If there is a need to calculate the Greatest Common Divisor for more than two numbers, you can calculate the GCD for the first two, then you pass to the method the next two numbers to check which will be the result of the first calculation and the third number. If you have more numbers you follow the same algorithm, the result so far and the next number until you check all numbers.
public static long Gcd(long x, long y)
{
while (y != 0)
{
long tmp = x % y;
x = y;
y = tmp;
}
return x;
}