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.