斐波那契数列 Fibonacci sequences(fei bo na qi):0、1、1、2、3、5、8、13、21、34……
递归算法:
1 def Fibonacci(n): 2 if n <= 1: return n 3 else: return Fibonacci(n - 1) + Fibonacci(n - 2)
迭代算法:
1 def Fibonacci(n): 2 if n <= 1: return n 3 else: 4 oneback,twoback = 1, 0 5 for i in range(2, n + 1): 6 current = twoback + oneback 7 twoback, oneback = oneback, current 8 return current
时间: 2024-10-08 22:12:16