斐波那契数列:0,1,1,2,3,5,8,13,...,求该数列第n项数字。
- 数列前两个数字 f(1)=0,f(2)=1
- 数列的每个数字是前两个数字之和
以下是两种不同的方法求第n项数字:循环迭代、递归
python
# 斐波那契数列:0,1,1,2,3,5,8,13,......,求该数列第n项数字
# 循环迭代
def fib(n: int) -> tuple:
"""
斐波那契数列:循环
:param n: 项数
:return:
"""
n1, n2 = 0, 1
n_list = [n1, n2]
for item in range(n - 2):
temp = n2
n2 = n1 + n2
n1 = temp
n_list.append(n2)
return n2, n_list
# 递归
def fib_plus(n: int) -> int:
"""
递归
:param n:
:return:
"""
# 终止条件
if n == 1 or n == 2:
return n - 1
# 递归调用
result = fib_plus(n - 1) + fib_plus(n - 2)
return result
if __name__ == '__main__':
num = fib(10)
print(num) # (34, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
num = fib_plus(10)
print(num) # 34