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);
}
}