Number of calls for nth Fibonacci number

后端 未结 6 2113
名媛妹妹
名媛妹妹 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:28

    phi is a constant

    position = ceil(log((n - 0.5)*sqrt(5))/log(phi));
    

    n is the fibonacci number... position will give you the which fibonacci number is n

    for example given 13 , position will be 7 - 0 1 1 2 3 5 8 13

    using this position just calculate the fibonacci number at position-1 or any position you want relative to given fibonacci number.

    Previous Fibo Num = floor((pow(phi,position-1)/sqrt(5))+0.5);
    

    floor((pow(phi, position)/sqrt(5))+0.5) - is the standard formula for calculating Nth fibonacci num (Note - This is not an approximation)

    I have just reverse this formula to calculate the position and use the position - 1 to calculate the previous fibonacci number.

    Ref - http://itpian.com/Coding/20951-Given-the-Nth-fib-no-and-find-the--N-1-th-fib-number-without-calculating-from-the-beginning---------.aspx

提交回复
热议问题