bash 递归算法 比较

一个阶乘的递归算法

#!/bin/bash
function recursive()
{
local i=$1
if [ $i -eq 0 ];then
num=1
else
recursive `expr $i – 1`
num=`expr $i * $num`
fi
return $num
}
recursive $1
echo $num

#!/bin/bash
function recursive()
{
local i=$1
if [ $i -eq 0 ];then
num=1
else
recursive $[ $i – 1 ]
num=$[ $i * $num ]
fi
return $num
}
recursive $1
echo $num

用循环语句来做阶乘

#!/bin/bash
if [ -z $1 ];then
echo "Need one parameter"
exit 1
elif [ $1 -gt 20 -o $1 -lt 1 ];then
echo "Number please Enter 1-20"
exit 1
fi
i=$1
num=1
until [ $i -eq 0 ]
do
let num=$num*$i
((i-=1))
done
echo $num

前两种只是写法上有所不同,其实是一样的,第三种加入了参数验证,使用起来更安全.
循环比递归开销小,递归代码量小但开销惊人,用哪种自己看着办吧
因为我的电脑是64位的,寄存器最大是可以放下2^64=18446744073709551616所以只能算到20的阶乘
看脚本的执行过程可以用bash -x ./xxxx.sh 5

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注