Java recursion and two variables

I've been trying to figure out how the stack of this recursive method works

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 clearly neither true nor complete Please help me understand how the stack is built

Solution

Theory:

Each time, this function will first decrement the Q1 (x / 2) path until the end condition is reached Then, all pending Q1 (x - 2) calls will be processed Now this is where it gets tricky. In each Q1 (X-2), we first deal with Q1 (x / 2) Therefore, we now return to the same place as before, with only one layer, and repeat until we process all Q1 (X-2) calls (in the last Q1 (x / 2) layer)

One way to think of it is like a tree:

You are right. If you pass the above, you mean that this function is much faster in Q1 (x / 2) than in Q1 (X-2) What you mean, however, is that it grows in the form of LG (n) (LG (n) is base 2)

However, we still need to analyze other stack frames, so we set the following repetition relationship:

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>