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

#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

long long fib(long n)
{
	//波那契数列 递归法 
	if(n<=2)
	{
		return 1;
	}
	return fib(n-1)+fib(n-2);
} 

long long Iterative_fib(long n)
{
	//波那契数列 迭代法 
	long a,b,c = 0; 
	b = 1;
	c = 1;
	if(n<=0){
		return 0;
	}
	switch(n)
	{
		case 1:return 1;
		case 2:return 1;
	}
	for(int i=2;i<=n;i++){
		a = c;
		c = b + c;
		b = a;
	}
	return c;
} 
posted @ 2024-03-19 21:10  Mask_2022  阅读(34)  评论(0)    收藏  举报