最近学习linux shell函数方面的知识,接触到递归函数,于是写了求阶乘和求汉诺塔的脚本。
1、求阶乘的脚本
#! /bin/bash
function jiecheng()
{
local n=$1
if [ "$1" -eq "1" ];then
result=1
else
temp=$((n-1))
jiecheng $temp
result=$((n*$result))
fi
}
jiecheng $1
echo "The total of $1 is $result"
2、求汉诺塔的脚本
#! /bin/bash
function hanoi()
{
local num=$1
if [ "$num" -eq "1" ];then
echo "Move:$2----->$4"
else
hanoi $((num-1)) $2 $4 $3
echo "Move:$2----->$4"
hanoi $((num-1)) $3 $2 $4
fi
}
hanoi $1 $2 $3 $4