标签: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 . . .从运行结果可以看出,非递归的方式求斐波那契数列效率远高于递归的求法
标签:blog os io ar for 2014 art cti sp
原文地址:http://blog.csdn.net/wyj7260/article/details/39100753