Number of calls for nth Fibonacci number

后端 未结 6 2109
名媛妹妹
名媛妹妹 2020-12-30 12:09

Consider the following code snippet:

int fib(int N)
{
   if(N<2) return 1;
   return (fib(N-1) + fib(N-2));
}

Given that fib

6条回答
  •  天涯浪人
    2020-12-30 12:53

    As mentioned above, you need to solve the following recurring equation: K(n)=K(n-1)+K(n-2)+1

    Let's write it for n-1: K(n-1)=K(n-2)+K(n-3)+1

    Now, subtract the second one from the first one: K(n)-K(n-1) = K(n-1) - K(n-3),

    or

    K(n) - 2*K(n-1) + K(n-3) = 0.

    The respective characteristic equation will be: x^3 - 2*x^2 + 1 = 0.

    It has the following roots: 1, (1+sqrt(5))/2, (1-sqrt(5))/2

    Thus for any real A,B,C the following function K(n) = A*(1)^n + B*((1+sqrt(5))/2)^n + C*((1-sqrt(5))/2)^n

    will be a solution for your equation.

    To find A,B,C you need to define several initial values K(0), K(1), K(2) and solve the system of equations.

提交回复
热议问题