Recursive Fibonacci

前端 未结 13 1662
情歌与酒
情歌与酒 2020-12-07 18:52

I\'m having a hard time understanding why

#include 

using namespace std;

int fib(int x) {
    if (x == 1) {
        return 1;
    } else {
         


        
13条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 19:28

    Why not use iterative algorithm?

    int fib(int n)
    {
        int a = 1, b = 1;
        for (int i = 3; i <= n; i++) {
            int c = a + b;
            a = b;
            b = c;
        }           
        return b;
    }
    

提交回复
热议问题