0

I want to know how this code#1 works so confusing... Can somebody explain how this gcd method returns something?

public class GCDFinder {
    //code#1
    public int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }   
    
    public static void main(String[] args) {
        System.out.println(new GCDFinder().gcd(4, 12)); // should print 5
    }
}

Meanwhile, I tried my own code using addition to understand this concept but I would get an error.

public class Compute  {
    public int gcd(int a, int b) {
        if(b==0) {
            return a;
        }
        return gcd(b,b+a);
    }
}
ratRiot01
  • 11
  • 3
  • 1
    The word you're looking for is "recursion". And it's returning the *result* of the function (method, actually), not the function itself. – Federico klez Culloca Sep 25 '20 at 10:30
  • Those are recursive functions. The second one gives you an error because you are calling it with `b != 0` and then you pass `b+a` as the `b` parameter, so `b` can never be 0 and thus it iterates eternally. – JustAnotherDeveloper Sep 25 '20 at 10:32
  • You said that it will return the result of the function... but that's where I'm confused. How does it return something? It's like returning method(a,b) without the method body... so confusing. Can you explain how code#1 works? – ratRiot01 Sep 25 '20 at 10:37
  • @ratRiot01 When you do `return method(parameter);`, it first runs `method(parameter)` and then it runs `return` with the result of the execution of the method. It's functionally equivalent to assigning the return of the method to a variable and returning that variable. The fact that the method you are calling is the same one where the `return` statement is doesn't matter to Java, it just runs the instructions. – JustAnotherDeveloper Sep 25 '20 at 10:45

0 Answers0