6.编写程序,定义一个求斐波那契数列的函数fib(n),并编写测试代码,输出前20项(每项宽度5个字符位置,右对齐),每行输出10个。请分别用递归和非递归方式实现。运行结果如下:
时间: 2024-05-14 09:15:27 浏览: 106
递归方式实现:
```python
def fib_recursive(n):
if n == 0 or n == 1:
return n
else:
return fib_recursive(n-1) + fib_recursive(n-2)
print("Fibonacci sequence (recursive):")
for i in range(20):
if i % 10 == 0:
print()
print("{:>5}".format(fib_recursive(i)), end="")
```
运行结果:
```
Fibonacci sequence (recursive):
0 1 1 2 3 5 8 13 21 34
55 89 144 233 377 610 987 1597 2584 4181
```
非递归方式实现:
```python
def fib_iterative(n):
if n == 0 or n == 1:
return n
else:
a, b = 0, 1
for i in range(2, n+1):
c = a + b
a, b = b, c
return c
print("Fibonacci sequence (iterative):")
for i in range(20):
if i % 10 == 0:
print()
print("{:>5}".format(fib_iterative(i)), end="")
```
运行结果:
```
Fibonacci sequence (iterative):
0 1 1 2 3 5 8 13 21 34
55 89 144 233 377 610 987 1597 2584 4181
```
阅读全文