Search code examples
javarecursionreturn

Java: Why my Euclid GCD function returns incorrect value


I am new to programming and I am learning Java using Think Java. I am trying to do exercise 10 of chapter 6. The exercise deals with writing a recursive function for finding the greatest common divisor (GCD) using Euclid Algorithm. I came up with 2 ideas. I am not sure why my second idea returns an incorrect value.

This idea works fine:

public class exercise10 {
    public static int gcd(int a, int b) {
        if (b == 0) return a;
        else return gcd(b, a % b);
    }
    public static void main(String[] arguments){
        System.out.println(gcd(36,20));
    }
}

This idea returns an incorrect value:

public class exercise10 {
    public static int gcd(int a, int b) {
        if (b > 0) {
            int r = a % b;
            gcd(b, r);
        }
        return a;
    }
    public static void main(String[] arguments){
        System.out.println(gcd(36,20));
    }

}

This is not part of any class homework. I am simply using the open-source textbook to learn java on my own.

Running java version 1.7.0_51 on Win64 machine


Solution

  • BorisTheSpider had pointed out what was wrong with my code but his post somehow got deleted. Anyway, he pointed out that my second idea was missing a return statement in front of the recursive function gcd(b, r).

    public class exercise10 {
        public static int gcd(int a, int b) {
            if (b > 0) {
                int r = a % b;
                gcd(b, r); <--- missing return
            }
            return a;
        }
        public static void main(String[] arguments){
            System.out.println(gcd(36,20));
        }
    
    }
    

    So the correct code should be:

    public class exercise10 {
        public static int gcd(int a, int b) {
            if (b > 0) {
                int r = a % b;
                return gcd(b, r);
            }
            return a;
        }
        public static void main(String[] arguments){
            System.out.println(gcd(36,20));
        }
    
    }
    

    Credits to BorisTheSpider.