In this post we show how to implement GCD in Java using Euclidean Algorithm. GCD is known as Greatest Common Divisor/Factor/Measure, Highest Common Divisor/Factor.

Greatest Common Divisor of integers is the largest positive integer that divides the numbers without a reminder. There are many ways to calculate GCD, but in this post we’re going to implement Euclidean Algorithm in a few different ways. The Euclidean algorithm is know for about 2300 years and it’s still used today.

How it works

GCD(a, b) works as follows:

If b is 0 then, a is GCD, because any number is divisor of 0 and the greatest divisor of a is |a|.

The result is GCD(b, a mod b), because the greatest common divisor doesn’t change when the larger number is replaced with it’s difference with the smaller number.

Euclidean algorithm – recursively

Recursive version is the simplest implementation of Euclidean algorithm: