Returns the nth Number of the Fibonacci sequence.

Source: Internet
Author: User

The Fibonacci sequence is defined as follows in recursion:

F0 = 0, F1 = 1

Fn = f (n-1) + f (n-2) (N> = 2, N *)

1. The simplest method for solving the Fibonacci series is recursive. The best time complexity is O (n ).

2. the Fibonacci series also has its own production formula:F (n) = (√ 5/5) * {[(1 + √ 5)/2] ^ N-[(1-√ 5)/2] ^ n }, the power query problem is involved here. We can use the divide and conquer method to solve the problem. complexity O (lgn)

3. In addition, the Fibonacci series can also use the matrix method,Sums of "Shallow" diagonals inPascal's
Triangle

Here we adopt the simplest method of recursive solution. The complexity of recursion is different from that of the top-down space.

 
# Include "stdafx. H "# include <iostream> using namespace STD; int Fibonacci (int n) // The disadvantage is that you need to apply for N integer spaces {int * result = (int *) malloc (sizeof (INT) * n + 1); Result [0] = 0; Result [1] = 1; if (n <2) return result [N]; for (INT I = 2; I <= N; I ++) result [I] = Result [I-1] + result [I-2]; return result [N];} int fibonacci2 (int n) // do not need to apply for space of O (n) {If (n = 0) return 0; If (n = 1) return 1; int first = 0; int second = 1; int result = 0; For (INT I = 2; I <= N; I ++) {result = first + second; first = Second; second = result;} return result;} int main () {cout <fibonacci2 (12); getchar (); Return 0 ;}

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.