Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java recursion with two variables

Tags:

java

recursion

I've been trying to figure out how the stack of this recursive method will look like.

public class Apples {

    public static void main (String [] args) {
       q1(5);   
    }

    public static int q1 (int x) {
        if (x < 1) {
            System.out.println(x);
            return 1;
        }
        int a = 3 + q1(x / 2);
        int b = 2 * q1(x - 2) + 1;
        System.out.println(x + ";" + a + ";" + b);
        return a + b;
    }
}

But so far, I only think that the stack grows according to x/2:

x=0   returns 1;
x=1  a=4  b=3     returns 7;
x=2  a=10 b=3     returns 13;
x=5  a=16 b=9     returns 19;

This is obviously neither true nor complete. Please help me understand how does the stack build up.

like image 202
dc36 Avatar asked Aug 04 '15 03:08

dc36


People also ask

Can you have 2 base cases for recursion?

A recursive implementation may have more than one base case, or more than one recursive step. For example, the Fibonacci function has two base cases, n=0 and n=1.

What is the common problem with recursive methods in Java?

Another common problem is to include within a recursive function a recursive call to solve a subproblem that is not smaller than the original problem. For example, the recursive function in NoConvergence. java goes into an infinite recursive loop for any value of its argument (except 1).

What is multiple recursion in Java?

We are in the presence of multiple recursion when the activation of a method can cause more than one recursive activations of the same method. Example: Recursive method for computing the n-th Fibonacci number.

Is there a limit for recursion for Java?

No, there is no setting to limit the recursion depth in Java.


1 Answers

Theory:

Each time, this function will recurse down the q1(x/2) path first, until it reaches the ending condition. Then, all pending q1(x-2) calls will be handled. Now this is where it gets tricky, at every q1(x-2) we first handle q1(x/2). Thus, we are now back to the same spot as before, just one layer down, repeating until we handle all the q1(x-2) calls (in the last q1(x/2) layer).

One way to think of it is like a tree:

3 layers of the recursion tree. (c) The Brofessor

I only think that the stack grows according to x/2

You are right, if by the above you mean that this function recurses much faster in the q1(x/2) than in the q1(x-2) direction. Nonetheless, what you are saying implies it grows in lg(n) fashion (lg(n) is base 2).

However, we still need to analyze the other stack frames, so we set up the following recurrence relation:

T(n) = T(n/2) + T(n-2) + c1

like image 193
The Brofessor Avatar answered Sep 28 '22 20:09

The Brofessor