Is there a better code for printing fibonacci series?

后端 未结 3 993
粉色の甜心
粉色の甜心 2020-12-12 08:14

Is the algorithm below the best way of generating the Fibonacci series? Or is there a better approach?

This is my C program to print fibonacci series.



        
3条回答
  •  暖寄归人
    2020-12-12 08:34

    This is optimal in terms of time complexity and space complexity, and much faster than the naive recursive algorithm, which is exponential in terms of run time.

    It does look as though your assignments in your loop aren't quite right, though. You want

    int oldi = i;
    i = n+i;
    n = oldi;
    

    HOWEVER, your approach has a crucial weakness, which is that you will quickly overflow the bounds of an int. Even with a 64-bit value, you'll get wrong answers by the time you hit f(100).

    To get correct answers with arbitrary indices, you will need an arbitrary size integer library.

    A related issue came up yesterday with calculating the Fibonacci series in Go.

提交回复
热议问题