/*
斐波那契数列 递归算法和非递归算法
f(0) = 0;
f(1) = 1;
f(n) = f(n - 1) + f(n - 2);
*/
#include<iostream>
#include<vector>
using namespace std;
// 递归算法
int Fun1(int n)
{
if(n == 0)
return 0;
else if(n == 1)
return 1;
else return Fun1(n - 1) + Fun1(n - 2);
}
// 非递归算法
int Fun2(int n)
{
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
{
int i = 2;
int temp1;
int temp2;
int sum;
temp1 = 0;
temp2 = 1;
while(i <= n)
{
sum = temp1 + temp2;
i++;
temp1 = temp2;
temp2 = sum;
}
return sum;
}
}
int main()
{
cout<<Fun1(20)<<endl;
cout<<Fun2(20)<<endl;
return 0;
}
斐波那契数列 递归算法和非递归算法
最新推荐文章于 2024-09-20 22:03:09 发布