Multiple implementation methods of the Fibonacci series

Source: Internet
Author: User
Problem

The Fibonacci series (Italian: successione di Fibonacci) are also translated into the Fibonacci numbers, the Fibonacci series, the Fibonacci series, and the Golden split series.

In mathematics, the Fibonacci series are defined by recursion:

F0 = 0 (n=0)F1 = 1 (n=1)Fn = F[n-1]+ F[n-2](n=>2)

For a wonderful explanation of Fibonacci, see the following video:

Ted-The Magic Fibonacci sequence: Success.

For more information, see wikipedia entry: Fibonacci series.


Ideas


Almost all advanced languages use the Fibonacci series as an example to explain concepts such as recursion and loops. Here, I want to use python to demonstrate various methods for your reference.


Solution (Python)


Recursion-write directly according to definition


This method is not a good method, because it has a high overhead, such as computing fiber 1 (100), it takes a long time to wait. Therefore, this is not a practical method. However, because the idea is simple, it is listed as the first one.

def fib1(n):    if n==0:        return 0    elif n==1:        return 1    else:        return fib1(n-1) + fib1(n-2)

Recursion and initialization


This is because the previous project has to be computed every time. Here, the above algorithm is slightly improved. The speed is much faster.

memo = {0:0, 1:1}def fib2(n):    if not n in memo:        memo[n] = fib2(n-1)+fib2(n-2)    return memo[n]

Iteration

This is also a simple and direct method.

def fib3(n):    a, b = 0, 1    for i in range(n):        a, b = b, a+b    return a

Use mathematical conclusions directly


The entries in Wikipedia have already listed the mathematical results of different forms of the Fibonacci series. You can take these results directly and use the program to calculate the Fibonacci number. This program is omitted in this 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.