斐波那契数列(递归)python
时间: 2024-05-22 18:09:41 浏览: 131
斐波那契数列是指:0、1、1、2、3、5、8、13、21、34、……
也就是前两项为 0 和 1,从第三项开始,每一项都等于前两项之和。
递归是一种编程技巧,指的是函数自己调用自己的过程。在斐波那契数列中,递归可以用以下代码来实现:
```
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
```
上述代码中,如果要计算第 n 个斐波那契数列的值,我们需要先判断 n 的大小,如果 n 小于等于 0,返回 0;如果 n 等于 1,返回 1;否则,递归地调用 fibonacci 函数计算第 n-1 和 n-2 个斐波那契数列的值,然后将它们相加得到第 n 个斐波那契数列的值。
相关问题
python编写递归函数和非递归函数、输出斐波那契数列_python 入门之斐波那契数列递归表达式算法和非递归算法...
好的,下面是Python实现斐波那契数列的递归和非递归算法:
递归算法:
```python
def fibonacci_recursive(n):
if n <= 1:
return n
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
```
非递归算法:
```python
def fibonacci_iterative(n):
if n <= 1:
return n
else:
a, b = 0, 1
for i in range(2, n+1):
c = a + b
a, b = b, c
return b
```
在这两个函数中,变量n表示要求的斐波那契数列的第n项。递归算法中,如果n小于等于1,则返回n;否则递归调用函数本身来计算前两项的和。非递归算法中,如果n小于等于1,则返回n;否则通过循环计算前两项的和,并不断更新前一项和当前项的值。
接下来,我们可以通过调用这两个函数来输出斐波那契数列的前n项:
```python
n = 10
# 递归算法
print("斐波那契数列(递归算法):")
for i in range(n):
print(fibonacci_recursive(i), end=" ")
print()
# 非递归算法
print("斐波那契数列(非递归算法):")
for i in range(n):
print(fibonacci_iterative(i), end=" ")
```
输出结果如下:
```
斐波那契数列(递归算法):
0 1 1 2 3 5 8 13 21 34
斐波那契数列(非递归算法):
0 1 1 2 3 5 8 13 21 34
```
这样就可以输出斐波那契数列的前n项了。
斐波那契数列非递归Python
斐波那契数列是指:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...,即从第三项开始,每一项都等于前两项之和。非递归的斐波那契数列可以使用循环来实现,代码如下:
```
def fibonacci(n):
if n < 1:
return None
if n == 1 or n == 2:
return 1
a, b = 1, 1
for i in range(3, n+1):
c = a + b
a = b
b = c
return c
```
其中,变量 a 和 b 分别用来表示当前计算的斐波那契数列的前两项,变量 c 表示当前计算的斐波那契数列的第 i 项。循环从第三项开始计算,依次计算每一项,并更新 a、b 和 c 的值。最后返回 c 即可。
阅读全文
相关推荐











