一、递归算法
#include<iostream>
using namespace std;
unsigned long Fibonacci(unsigned long);
int main()
{
for ( int counter=0 ; counter < 20 ; counter++ )//这里只求一下20以内的斐波那契数列
cout << "Fibonacci(" << counter << ")=" << Fibonacci(counter) <<endl;
}
unsigned long Fibonacci (unsigned long counter)
{
if (counter>1)
return Fibonacci(counter-1)+Fibonacci(counter-2);
else if (counter==1)
return 1;
else if (counter==0)
return 0;
}
二、迭代算法
#include<iostream>
using namespace std;
int main()
{
unsigned long Fibonacci_n=0,fibonacci_2=1,fibonacci_1=0;
for(int counter=0;counter<20;++counter)//同样只求一下前20个数
{
if(counter<2)
cout << "Fibonacci(" << counter << ")=" << counter <<endl;
else
{
fibonacci_1=Fibonacci_n;
Fibonacci_n=fibonacci_1+fibonacci_2;
fibonacci_2=fibonacci_1;
cout << "Fibonacci(" << counter << ")=" << Fibonacci_n <<endl;
}
}
}