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