#include<iostream.h>
#include <stdio.h>
//vc++无法定义long long类型
//报错:error C2632: 'long' followed by 'long' is illegal
//递归算法
unsigned long Fibonacci1(unsigned n)
{
if(n<=0)
return 0;
if(n==1)
return 1;
return Fibonacci1(n-1)+Fibonacci1(n-2);
}
//非递归算法
unsigned long Fibonacci2(unsigned n)
{
int result[2]={0,1};
if(n<2)
return result[n];
unsigned long one=1;
unsigned long two=0;
unsigned long fibN=0;
for(unsigned int i=2;i<=n; i++)
{
fibN=one+two;
one=fibN;
two=one;
}
return fibN;
}
//==============测试用例=========
void Test(int n, unsigned long expected)
{
if(Fibonacci1(n) == expected)
printf("Test for %d in solution1 passed.\n", n);
else
printf("Test for %d in solution1 failed.\n", n);
if(Fibonacci2(n) == expected)
printf("Test for %d in solution2 passed.\n", n);
else
printf("Test for %d in solution2 failed.\n", n);
}
void main()
{
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);
}
【剑指offer】裴波那契数列算法09
最新推荐文章于 2019-09-22 11:44:22 发布