码迷,mamicode.com
首页 > 其他好文 > 详细

09_斐波那契数列

时间:2014-09-06 14:54:03      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:blog   os   io   ar   for   2014   art   cti   sp   

#include<iostream>
#include<vector>
#include<Ctime> 
using namespace std;

long long fibRecursion(unsigned n) {

	if(n <= 0) {
		return 0LL;
	} 
	
	if(n == 1) {
		return 1LL;
	}
	
	if(n >= 2) {
		return fibRecursion(n - 1) + fibRecursion(n -2);
	}		
} 

long long fibUnRecursion(unsigned n) {
	
	if(n == 0) {
		return 0LL;
	} 
	
	if(n == 1) {
		return 1LL;
	}
	
	long long fibNSmaller = 0LL;
	long long fibNBigger = 1LL;
	long long fibN = 0LL;
	
	unsigned i = 2;
	for(i = 2; i <= n; i++){
		fibN = fibNSmaller + fibNBigger;
		fibNSmaller = fibNBigger;
		fibNBigger = fibN;
	}
	
	return fibN;
	
} 


int main() {
	
	unsigned i = 0;
    clock_t start, finish; 
    
    start = clock();
	cout<<"fibRecursion(46) = "<<fibRecursion(45)<<endl;
	finish = clock();
	double duration = (double)(finish - start) / CLOCKS_PER_SEC;
	cout<<"execution time duration(fibRecursion):"<<duration<<endl;
	
	
	
	start = clock();
	cout<<"fibUnRecursion(46) = "<<fibUnRecursion(45)<<endl;
	finish = clock();	
	duration = (double)(finish - start) / CLOCKS_PER_SEC;
	cout<<"execution time duration(fibUnRecursion):"<<duration<<endl;
	
return 1;
}



运行结果:

fibRecursion(46) = 1134903170
execution time duration(fibRecursion):11.603
fibUnRecursion(46) = 1134903170
execution time duration(fibUnRecursion):0.001

--------------------------------
Process exited with return value 0
Press any key to continue . . .
从运行结果可以看出,非递归的方式求斐波那契数列效率远高于递归的求法

09_斐波那契数列

标签:blog   os   io   ar   for   2014   art   cti   sp   

原文地址:http://blog.csdn.net/wyj7260/article/details/39100753

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!