斐波那契数列的实现
数学结构:
![](https://i-blog.csdnimg.cn/blog_migrate/80b5b2babce9f11203fc43a608e555ab.png)
#include <stdio.h>
#include <iostream>
using namespace std;
//递归表达式 数据大时 耗时会特别长 还可能发生栈溢出
long Fbi2(int i)
{
if (i < 2)
return (i == 0 ? 0 : 1);
return Fbi2(i - 1) + Fbi2(i - 2);
}
//改进版 先根据f(0)和f(1)算出f(2) 在根据f(1)和f(2)算出f(3)
//依次往下计算算出第n项
long long Fbi1(int n)
{
int result[2] = { 0, 1 };
if (n < 2)
return result[n];
long long sum = 0;
long long fbfirst = 0;
long long fbsecond = 1;
for (unsigned int i = 2; i <= n; ++i)
{
sum = fbfirst + fbsecond; //求和
//下面俩句相当于将fbfirst和fbsecond依次往后移动
fbfirst = fbsecond;
fbsecond = sum;
}
return sum;
}
int main(int argc,char *argv[])
{
for (int i = 0; i < 40; i++)
{
cout << Fbi1(i) << endl;
}
for (int i = 0; i < 40; i++)
{
cout << Fbi2(i) << endl;
}
return 0;
}