现在的位置: 首页 > 综合 > 正文

求斐波那契数列的两种解法

2013年06月11日 ⁄ 综合 ⁄ 共 974字 ⁄ 字号 评论关闭

下面代码仅供本人复习所用,实用性N低,各位飘过吧~~哈哈:>

//
// 斐波那契数列. 
// 
// 斐波那契数列指的是类似于这样的一个数列:
//   1, 1, 2, 3, 5, 8, 13, 21...
// 该数列从第 3 项开始,每一项都等于前两项之和. 
//

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <stdexcept>

//
// 递归方法计算斐波那契数列. 
// 
unsigned long fibonacci_recursion(const unsigned long n)
{
	unsigned long number;
	
	if (1 == n || 2 == n) {
		number = 1;
	}
	else {
		number = fibonacci_recursion(n - 1) 
 			   + fibonacci_recursion(n - 2);
	}
	return number;
} 

//
// 迭代方法计算斐波那契数列. 
//
unsigned long fibonacci_iteration(const unsigned long n)
{	
	unsigned long result = 1;
	
	if (2 < n) 
	{
		unsigned long first = 1, second = 1, i = 3;
		
		do {
			result = first + second; 
			first = second;
			second = result;
		} while (++i <= n);
	}
	
	return result;
} 

//
// 测试. 
//
int main(void)
{
	
	unsigned long n;
	
	std::cout << "How long the Fibonacci sequence you want: ";
	while (!(std::cin >> n) || 1 > n)
	{
		std::cin.clear();
		std::cin.sync();
		std::cout << "Input Wrong, Please Input Again: "; 
	} 
	
	clock_t start = clock();
	for (size_t i = 1; i <= n; ++i)
	{
		std::cout << fibonacci_iteration(i) << " ";
	}
	clock_t finish = clock();

	std::cout << std::endl;
	std::cout << "Elapsed time: " << finish - start << std::endl;
	return EXIT_SUCCESS;
}

抱歉!评论已关闭.