Java Code Example: greatest common divisor (recursion)

The gcd of two numbers is the greatest common divisor of these numbers, that is the greatest number by which both numbers are divisible.

public class GreatestCommonDivisor {
    static int gcd(int a, int b) {
        if (a == 0) {
            return b;
        } else if (b == 0) {
            return a;
        } else if (a > b) {
            return gcd(a - b, b);
        } else {
            return gcd(a, b - a);
        }
    }

    public static void main(String[] args) {
        int a = 120, b = 45;

        System.out.println("Greatest common divisor is: " + gcd(a, b));
    }
}
Output
Greatest common divisor is: 15