斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368......这个数列从第3项开始,每一项都等于前两项之和
方法一:(递归)
def fib(n):
assert n >= 0, "n > 0"
if n <= 1:
return n
else:
return fib(n-1) + fib(n-2)
for i in range(1, 20000):
print(fib(i), end=' ')
方法二:(循环)
def fib(n):
a = 1
b = 1
while a <= n:
print(a, end=" ", flush=True)
a, b = b, a+b
fib(1000000)
网友评论