简体   繁体   中英

Java output of a recursive method

New to recursion. The output of this code is 79 , How is this answer reached? When written down I find the base case never being reached. (-3+4) + (2 * -3) = -5 => (-5+4) + (2 * -5) = -11... Do I have a fundamental misunderstanding of recursion or basic algebra?

int result = negative(-3);

public int negative(int num)
{
    if(num >= 20)
    {
        return -5;
    }
    else
    {
        return negative(num + 4) + 2 * num;
    }
}

public void print()
{
    System.out.println("The final answer is " +result);
}

Your first case isn't (-3+4) it's negative(-3+4) which is negative(1) + (2 * -3). If you change the first line of negative to

System.out.println(num);

You can see how the numbers recursively reach the output you've already given.

Try writing this out yourself:

If the function is sent a number greater than, or equal to 20, it returns -5

Otherwise, it returns 2*num + (itself again with num+4)

We get:

(2*-3) + (2*1) + (2*5) + (2*9) + (2*13) + (2*17) + (-5)

Doing the above, you get 74

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM