public static int foo(int a, int b) {
if (b < a) {
return foo(b, a);
}
if ((b/a)*a == b) {
return a;
}
return foo(a, b-a);
}
What is the value of calling foo(2, 7);
Open another tab so you can read the following walk-through while also looking at the code to see what is happening.
Start of foo: a (2), b (7)
_________________________
Checking to see if b (7) is less than a (2)
b (7) is not less than a (2), continuing...
Checking to see if (b (7) / a (2)) * a (2) == b
(7 / 2) * 2 = 6
They were not equal so now we are going to call foo(2, 5)
_________________________
Start of foo: a (2), b (5)
_________________________
Checking to see if b (5) is less than a (2)
b (5) is not less than a (2), continuing...
Checking to see if (b (5) / a (2)) * a (2) == b
(5 / 2) * 2 = 4
They were not equal so now we are going to call foo(2, 3)
_________________________
Start of foo: a (2), b (3)
_________________________
Checking to see if b (3) is less than a (2)
b (3) is not less than a (2), continuing...
Checking to see if (b (3) / a (2)) * a (2) == b
(3 / 2) * 2 = 2
They were not equal so now we are going to call foo(2, 1)
_________________________
Start of foo: a (2), b (1)
_________________________
Checking to see if b (1) is less than a (2)
b (1) is less than a (2), calling foo(1, 2);
_________________________
Start of foo: a (1), b (2)
_________________________
Checking to see if b (2) is less than a (1)
b (2) is not less than a (1), continuing...
Checking to see if (b (2) / a (1)) * a (1) == b
(2 / 1) * 1 = 2
They are equal so we just return a (1)