作者:小小是小小小 | 来源:互联网 | 2021-12-12 18:30
代码如下:
采用递归形式和非递归形式实现斐波那契数列
代码如下:
#include "stdafx.h"
#include
using namespace std;
//递归形式的斐波那契数列
int fibonacciRecursion(int n)
{
if (n == 1 || n ==2)
{
return 1;
}
if (n > 2)
{
return fibonacciRecursion(n - 1) + fibonacciRecursion(n - 2);
}
}
//非递归形式的斐波那契数列
//用一个数组作为辅助的空间
//效率较高
int fibonacci(int n)
{
int temp[2];
temp[0] = 1;
temp[1] = 1;
if (n == 1 || n == 2)
{
return 1;
}
else
{
for (int i = 2; i {
int tp = temp[0] + temp[1];
temp[1] = temp[0];
temp[0] = tp;
}
return temp[0];
}
}
测试代码:
代码如下:
int _tmain(int argc, _TCHAR* argv[])
{
cout < < < cout < fibonacciRecursion(4) <<" "< <<" "< return 0;
}