Python development [algorithm]: time complexity of the Fibonacci series, python Fibonacci
Fibonacci Series
Overview:
The Fibonacci series, also known as the Golden split series, refers to a series of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ,...... In mathematics, the Fibonacci sequence is defined as follows in a recursive method: F (0) = 0, F (1) = 1, F (n) = F (n-1) + F (n-2) (n ≥ 2, n ε N *) in modern physics, quasi-crystal structure, chemistry and other fields, Fibonacci series have direct application, therefore, the American Data society has published a mathematics magazine named the quarterly Fibonacci series since 1963 to publish research results in this area.
Solution:
F (n), which solves the Fibonacci series, has two common algorithms: recursive algorithm and non-recursive algorithm. Analyze the time complexity of the two algorithms.
1 Recursive Algorithm
#!/usr/bin/env python# -*- coding:utf-8 -*-def fibonacci(n): if n == 0: return 0 elif n <= 2: return 1 else: return fibonacci(n-1) + fibonacci(n-2)fibonacci(100)
Time Complexity: To solve F (n), we must first calculate F (n-1) and F (n-2), calculate F (n-1) and F (n-2 ), you must first calculate F (n-3) and F (n-4 )...... And so on until the values of F (1) and F (0) must be calculated first, and then the results of F (n-1) and F (n-2) are obtained in reverse order to obtain F (n) A lot of repeated values need to be calculated, which creates a great waste of time. The time complexity of the algorithm increases exponentially with the increase of N, and the time complexity is O (2 ^ n ), that is, the Npower of 2
2 Non-Recursive Algorithms
#!/usr/bin/env python# -*- coding:utf-8 -*-def fibonacci(n): if n == 0: return 0 elif n <= 2: return 1 else: num1 = 1 num2 = 1 for i in range(2,n-1): num2 = num2 + num1 num1 = num2 - num1 return num1 + num2print(fibonacci(100))
Algorithm complexity: From n> 2, the results are obtained by adding the numbers F (n-1) and F (n-2), which avoids a large number of repeated computations, it is much more efficient than recursive algorithms. The time complexity of algorithms is proportional to n, that is, the time complexity of algorithms is O (n)