0

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);
}
1
  • It's negative(num + 4) + (2 * num) not negative((num + 4) + (2 * num)). Commented Nov 5, 2014 at 3:46

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.