Here is a recursive static method in Java.
public static int mystery(int m, int n) {
int result = 1;
if (m > 0) {
result = n * mystery(m-1, n);
}
System.out.println (m + " " + result);
return result;
}
What will be printed to the standard output if we make the method call mystery(3,4)? What would be the final return value from the call to mystery(3,4)?
What is the explanation to the answer for the standard output part.
Output:
0 1
1 4
2 16
3 64
The final return value is 64.
Consider n to be fixed (which for all intents and purposes it is) and let f(m) be mystery(m,n).
Then
f(0) = 1
f(1) = n * f(0) = n
f(2) = n * f(1) = n * n
f(3) = n * f(2) = n * n * n
Can you see the general pattern? Can you give a closed form for f(n)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With