简体   繁体   中英

Recursive function to calculate greatest common divisor

I'm trying to implement a recursive function to calculate the gcd of two numbers, but my code is not working, any idea what's wrong?

public static int gcd(int a, int b) {
    if (a == b) {
        return a;
    }

    while (a != b) {
        if (a > b) {
            gcd(a - b, b);
        } else if (b > a) {
            gcd(a, b - a);
        }
    }
    return a;
}

You don't need the while loop if you are using recursion. Just do:

public static int gcd(int a, int b) {
    if (a == b) {
        return a;
    }

    if (a > b)
        return gcd(a - b, b);

    return gcd(a, b - a);
}

By the way, while (a != b) is an infinite loop if it is reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM