zoukankan      html  css  js  c++  java
  • 求斐波那契数列的两种解法

    下面代码仅供本人复习所用,实用性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;
    }
    
  • 相关阅读:
    读《人工智能的未来》
    人工智能的未来--分级时序记忆模型初探
    Cracking the coding interview--Q1.8
    Cracking the coding interview--Q1.7
    Cracking the coding interview--Q1.6
    Cracking the coding interview--Q1.4
    Cracking the coding interview--Q1.3
    Cracking the coding interview--Q1.2
    java系统库性能优化注意点
    java File.mkdirs和mkdir区别
  • 原文地址:https://www.cnblogs.com/wxxweb/p/2064894.html
Copyright © 2011-2022 走看看