首页 > 代码库 > 菲波那契数列编程实现

菲波那契数列编程实现

http://blog.csdn.net/pipisorry/article/details/37660419

斐波那契数列又因数学家列昂纳多·斐波那契以兔子繁殖为例子而引入,故又称为“兔子数列”。
fibonacci 数列定义:
n = 1,2 时,fib(n) = 1
n > 2 时,fib(n) = fib(n-2) + fib(n-1)

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584,……….


菲波那契数列编程实现:

/*	菲波那契数列递归实现	*/
int fibonacci(int index){
	if( index == 1 || index == 2 )
		return 1;
	return fibonacci(index - 2) + fibonacci(index - 1);
}

/*	菲波那契数列非递归实现1	*/
int fibonacci1(int index){					//1 0 1 1 2 3 5 ... (添加了1 0项)
	int sum = 0;
	int pre_pre_sum, pre_sum = 1;
	while(index--){
		pre_pre_sum = pre_sum;				//第n-2项的值
		pre_sum = sum;						//第n-1项的值
		sum = pre_sum + pre_pre_sum;		//第n项的值
	}
	return sum;
}

/*	菲波那契数列非递归实现2	*/
int fibonacci2(int index){					//-1 1 0 1 1 2 3 5 ... (添加了1 0项)
	int pre_pre_sum = -1, pre_sum = 1;
	while(index--){
		pre_sum = pre_sum + pre_pre_sum;	//第n-1项的值
		pre_pre_sum = pre_sum - pre_pre_sum;//第n-2项的值
	}
	return pre_sum + pre_pre_sum;			//第n项的值
}



from:http://blog.csdn.net/pipisorry/article/details/37660419

ref:递归与非递归的性能对比http://foofish.net/blog/65/fibonacci

实现2http://blog.csdn.net/qiao000_000/article/details/4856431