Using Python to find the nth item of the Fibonacci sequence

Source: Internet
Author: User

1. Background--fabonacci Series Introduction (from Baidu Encyclopedia):

The Fibonacci sequence (Fibonacci sequence), also known as the Golden Division sequence. Because the mathematician Leonardo's Fibonacci (Leonardoda Fibonacci) is introduced by the example of rabbit reproduction, it is also called "Rabbit series", referring to such a series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 、...... The formula is defined as follows:

The calculation formula is:

When n tends to infinity, the ratio of the previous item to the latter is getting closer to the Golden Section 0.618

2. Using Python iterations to solve the nth term of the Fibonacci sequence

def fib_iter (n):    n1 = 1    n2 = 1    n3 = 1    if (n < 1):        print ("Wrong input!")        Return-1    Else: while        (n-2) > 0:            n3 = n2 + N1            n1 = n2            n2 = N3            N-= 1    return n3result = Fib_iter (+) if result! =-1:    print (Result)

Advantages: When the n value is large, the solution speed is faster than the recursive method

Cons: Code is not simple and easy to understand

3. Using Python recursive implementation to solve the nth term of Fibonacci sequence

def fib_re (n):    result = 0    if (N < 1):        print ("Wrong input!")        Return-1    Else:        if (n = = 1 or n = = 2):            return 1        else:            return Fib_re (n-1) + fib_re (n-2) result = Fib_re (3 5) If result! =-1:    print (Result) #分治思想

Pros: Code is simple and easy to understand

Cons: When n values are large, repeated stack and stack operations allow for a long run time

Using Python to find the nth item of the Fibonacci sequence

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.