Mystery Method: Given a recursive method like:
public int recursiveFunctionA( int x, int y ){
if( x == 0 || y == 0 ){
return 0;
}else{
return x + recursiveFunctionA( y-1, x );
}
}
We can trace this recursive method with something like the following. Below are some example calls:
recursiveFunctionA(3, 2) returns 3 + recursiveFunctionA(1, 3)
recursiveFunctionA(1, 3) returns 1 + recursiveFunctionA(2, 1)
recursiveFunctionA(2, 1) returns 2 + recursiveFunctionA(0, 2)
recursiveFunctionA(0, 2) returns 0
recursiveFunctionA(2, 1) returns 2 + 0 = 2
recursiveFunctionA(1, 3) returns 1 + 2 = 3
recursiveFunctionA(3, 2) returns 3 + 3 = 6
recursiveFunctionA(1, 4) returns 1 + recursiveFunctionA(3, 1)
recursiveFunctionA(3, 1) returns 3 + recursiveFunctionA(0, 3)
recursiveFunctionA(0, 3) returns 0
recursiveFunctionA(3, 1) returns 3 + 0 = 3
recursiveFunctionA(1, 4) returns 1 + 3 = 4
recursiveFunctionA(3, 5) returns 3 + recursiveFunctionA(4, 3)
recursiveFunctionA(4, 3) returns 4 + recursiveFunctionA(2, 4)
recursiveFunctionA(2, 4) returns 2 + recursiveFunctionA(3, 2)
recursiveFunctionA(3, 2) returns 6 (from above)
recursiveFunctionA(2, 4) returns 2 + 6 = 8
recursiveFunctionA(4, 3) returns 4 + 8 = 12
recursiveFunctionA(3, 5) returns 3 + 12 = 15
recursiveFunctionA(0, 9) returns 0
It multiplies!
Consider the following recursive method below:
public int recursiveFunctionB( int a, int b ){
if( a < b ){
return 0;
}else{
return 1 + recursiveFunctionB( a - b, b );
}
}
Answer the following two questions:
- What is the value returned for each of the following method calls (Show the recursive method calls that are generated)?
- recursiveFunctionB( 7, 2);
- recursiveFunctionB( 29, 5);
- recursiveFunctionB( 5, 7);
- In just a few words, state what the method is computing (assuming a > 0 and b > 0 for the initial call).