Fibonacci sequence of C + + algorithm

Source: Internet
Author: User

Title: Write a function, enter N, and find the nth of the Fibonacci sequence.

Method 1: Recursion:

int fib2 (int n) {if (n = = 0)  return 0;if (n = = 1)  return 1;return fib2 (n-1) +fib2 (n-2);}

Cons: If n is large, then the degree of recursion is more deep

Method 2:

int fib (int n) {int result[2] = {0,1};if (n < 2) return result[n];int Fibone = 0;int fibtwo = 1;int fibn   = 0;int i = 0 ; for (i = 2; I <= n; i++) {fibn = Fibone + fibtwo;fibone = Fibtwo;fibtwo = fibn;} return fibn;}


The infinite recursion problem is avoided, and a cycle time complexity is O (n);

Fibonacci sequence of C + + algorithm

Related Article

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.