题目:
写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项。
思路:
无非两种思路,一种是递归,一种是循环。
由于n较大时,递归容易引起栈溢出,导致结果不正确或时间效率低下,所以还是首选循环。
另外有种基于生僻数学公式的矩阵算法,时间效率可达到O(logn),在这里就不介绍这种算法了
完整代码包含测试代码:
#include <iostream>
using namespace std;
long long Fibonacci_Solution1(unsigned int n)//递归
{
if (n <= 0)
return 0;
if (n == 1)
return 1;
return Fibonacci_Solution1(n - 1) + Fibonacci_Solution1(n - 2);
}
long long Fibonacci_Solution2(unsigned int n)//循环
{
if (n <= 0)
return 0;
if (n == 1||n==2)
return 1;
long long a = 1, b = 1;
long long res = 0;
for (int i = 3; i <= n;++i)
{
res = a + b;
b = a;
a = res;
}
return res;
}
// ====================测试代码====================
void Test(int n, int expected)
{
if (Fibonacci_Solution1(n) == expected)
printf("Test for %d in solution1 passed.\n", n);
else
printf("Test for %d in solution1 failed.\n", n);
if (Fibonacci_Solution2(n) == expected)
printf("Test for %d in solution2 passed.\n", n);
else
printf("Test for %d in solution2 failed.\n", n);
/*if (Fibonacci_Solution3(n) == expected)
printf("Test for %d in solution3 passed.\n", n);
else
printf("Test for %d in solution3 failed.\n", n);*/
}
int main(int argc, char* argv[])
{
Test(0, 0);
Test(1, 1);
Test(2, 1);
Test(3, 2);
Test(4, 3);
Test(5, 5);
Test(6, 8);
Test(7, 13);
Test(8, 21);
Test(9, 34);
Test(10, 55);
Test(40, 102334155);
system("pause");
return 0;
}