09 _ Fibonacci Series

Source: Internet
Author: User
#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;}


 

Running result:

fibRecursion(46) = 1134903170execution time duration(fibRecursion):11.603fibUnRecursion(46) = 1134903170execution time duration(fibUnRecursion):0.001--------------------------------Process exited with return value 0Press any key to continue . . .
From the running results, we can see that the non-recursive method is much more efficient than the recursive method in finding the Fibonacci sequence.

09 _ Fibonacci Series

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.