"Sword point offer" Fibonacci sequence (recursive and non-recursive implementations)

Source: Internet
Author: User

Recursive implementations are the most commonly thought-out approach, with the following code:

Recursive Way long Fibonacci (unsigned n) {if (n==0) {return 0;} else if (n==1) {return 1;} Else{return Fibonacci (n-1) +fibonacci (n-2);}}
Obviously recursion is not the best method, and when n is large, efficiency will be very low.

The good ideas are:

From the bottom up, F (2) is calculated based on F (0) and F (1), and F (2) is calculated according to F (1) and F (3). And so on, you can figure out the nth item. The time complexity of this idea is O (n).

Non-recursive Way long fibonaccitwo (unsigned n) {int result[2]={0,1};if (n<2) {return result[n];} Long F_nmisone=1;long f_nmistwo=0;long f=0;for (int i=2; i<=n; i++) {//f (n) =f (n-1) +f (n-2) f=f_nmisone+f_nmistwo;f_ Nmistwo=f_nmisone;f_nmisone=f;} return F;}

The first 21 elements of the output Fibonacci sequence are as follows:


"Sword point offer" Fibonacci sequence (recursive and non-recursive implementations)

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.