斐波那契数列的递归算法和迭代算法

一、递归算法

#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;
			}
	    }
}
    原文作者:递归算法
    原文地址: https://blog.csdn.net/Jin7_/article/details/75544930
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞