Python程序借助两种方法来计算斐波那契数列的第n个项 (有许多方法可以计算第n个项)。
描述:
第一种方法:动态编程
在这种方法中,我们计算出斐波那契数列直到n的所有项,如果我们需要计算小于n的任何其他项,则不必再次计算。
第二种方法:按公式
在这种方法中,我们借助公式计算斐波纳契数列的第n个项。
Formula:
phi = ( 1 + sqrt(5) ) / 2
An = phin/ sqrt(5)
例:
Input:
for n = 5
for n = 8
Output:
a5 = 5
a8 = 21
过程:动态编程方法
L[0] = 0, L[1] = 1
For loop from 2 to n+1
L[i] = L[i-1] + L[i -2]
End of for
如您所见,我们还存储了每个计算所得的值,因此以后也可以在必要时使用它们。
这是动态编程优于递归的优势。
Python代码可计算斐波那契数列的第n个项
def dynamic_fibonacci(n):
'''
This function will calculate fobonacci
series with the help of dynamic
programming.
'''
l = [0]*(n+1)
l[0] = 0
l[1] = 1
for i in range(2, n+1):
l[i] = l[i-1] + l[i-2]
return l
# Time complexity O(n)
def fibonacci_by_formula(n):
'''
This function will calculate n-th
term of fibonacci series with the
help of a formula.
'''
from math import sqrt
phi = (1 + sqrt(5))/2
fib = round(pow(phi, n)/sqrt(5))
return fib
# Time complexity O(1)
def main():
n = 8
lst = dynamic_fibonacci(n)
x = fibonacci_by_formula(n)
print('By Dynamic Programming:',lst[n])
print()
print('By Formula:',x)
main()
def dynamic_fibonacci(n):
'''
This function will calculate fobonacci
series with the help of dynamic
programming.
'''
l = [0]*(n+1)
l[0] = 0
l[1] = 1
for i in range(2, n+1):
l[i] = l[i-1] + l[i-2]
return l
# Time complexity O(n)
def fibonacci_by_formula(n):
'''
This function will calculate n-th
term of fibonacci series with the
help of a formula.
'''
from math import sqrt
phi = (1 + sqrt(5))/2
fib = round(pow(phi, n)/sqrt(5))
return fib
# Time complexity O(1)
def main():
n = 8
lst = dynamic_fibonacci(n)
x = fibonacci_by_formula(n)
print('By Dynamic Programming:',lst[n])
print()
print('By Formula:',x)
main()
输出量
By Dynamic Programming: 21
By Formula: 21
翻译自: https://www.includehelp.com/python/program-to-calculate-n-th-term-fibonacci-series.aspx
今日福利
????????
推荐阅读--