1

Question: How many calls are needed to recursively calculate the 7th Fibonacci value?

So this was a problem given to me and the answer was given to me as 41. Then I went to a professor because I didn't understand it, but I was given another answer. I think it was 25? (don't quote me on that) Then I went to another professor... and he told me the person who gave you this problem should have given you the sample code because there can be multiple ways to write this recursive function which would result in different amounts of calls.

So if this is true can you guys find different recursive functions that would result in a different amount of calls needed to get the 7th value of the sequence?

10
  • Look up Tail Recursion: gist.github.com/lazywithclass/1402456. This results in n number of calls where n = the nth Fibonacci value Commented Nov 20, 2015 at 2:28
  • Recursion is the wrong answer no matter what. You should use Dynamic Programming to solve this. Commented Nov 20, 2015 at 2:28
  • One niave approach and one using a memoization. Commented Nov 20, 2015 at 2:29
  • It depends how you write it. If you use memoization you can reduce the number of calls, but if you just do return n == 0 ? 0 : n == 1 ? 1 : fib(n - 1) + fib(n - 2); the number of calls is indeed 41. Commented Nov 20, 2015 at 2:30
  • This is answer to the correct problem, and is also the answer to the stated problem, with the answer "zero". Commented Nov 20, 2015 at 2:30

1 Answer 1

0

One way:

static long fibonacciR(int i)
{
    if (i <= 1)
        return i;
    return fibonacciR(i - 1) + fibonacciR(i - 2);
}

Another way:

static final int    f[] = {0,1,1,2,3,5,8,13,21,34,55,89,144};
static long fibonacciR2(int i)
{
    if (i < f.length)
        return f[i];
    return fibonacciR2(i-1)+fibonacciR2(i-2);
}

In fact 'another' way is any number of other ways, depending on how big you make the table. When the table has two elements both methods are equal. When it has three there are 25 calls. When 4, 15. And so on.

Yet another way, to get specifically 25 calls:

static long fibonacciR3(int i)
{
    if (i == 0)
        return 0;
    if (i <= 2)
        return 1;
    return fibonacciR(i - 1) + fibonacciR(i - 2);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.