Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Recursion Explanation

Tags:

java

recursion

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.

like image 484
JavaStudent12344 Avatar asked Aug 02 '26 04:08

JavaStudent12344


1 Answers

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)?

like image 163
Chris Taylor Avatar answered Aug 03 '26 18:08

Chris Taylor