斐波那契数列
python
def fibonacci(n):
if n <= 0:
return "Invalid input"
elif n == 1:
return 0
elif n == 2:
return 1
else:
prev_1 = 0
prev_2 = 1
for _ in range(n - 2):
current = prev_1 + prev_2
prev_1, prev_2 = prev_2, current
return prev_2
shell
#!/bin/bash
fibonacci() {
local n=$1
if [ $n -le 0 ]; then
echo "Invalid input"
elif [ $n -eq 1 ]; then
echo 0
elif [ $n -eq 2 ]; then
echo 1
else
prev_1=0
prev_2=1
for ((i=2; i<n; i++)); do
current=$((prev_1 + prev_2))
prev_1=$prev_2
prev_2=$current
done
echo $prev_2
fi
}
# 测试函数
echo $(fibonacci 5) # 输出:3
echo $(fibonacci 8) # 输出:13
阶乘
思路是一样的,只是算式不一样,代入几何坐标中会更好理解
python
def factorial(n):
if n < 0:
return "Invalid input"
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial(5)) # 输出:120
print(factorial(8)) # 输出:40320
shell
#!/bin/bash
factorial() {
local n=$1
if [ $n -lt 0 ]; then
echo "Invalid input"
elif [ $n -eq 0 ] || [ $n -eq 1 ]; then
echo 1
else
result=1
for ((i=2; i<=n; i++)); do
result=$((result * i))
done
echo $result
fi
}
# 测试函数
echo $(factorial 5) # 输出:120
echo $(factorial 8) # 输出:40320
标签:elif,factorial,echo,斐波,result,阶乘,那契,eq
From: https://www.cnblogs.com/dewan/p/17624385.html