对任意输入的正整数N,求N!的尾部连续0的个数,并指出计算复杂度如:18!尾部连续0的个数是3. (不用考虑数值超出计算机整数界限的问题)
这题我刚拿到的时候也是想先求阶乘,然后除10判断0个数,弄了半天其实总是出界^_^,换个角度想想如果这样算的话就不是百度,不是算法了.其实2的个数总是多余5的个数的,实际上也就是求5的个数了.代码这么插入貌似清晰些^_^
#!/bin/bash
#count Factorial Zero
echo "Please input the number to count:"
read number
if [ $number -le 5 ]
then
echo "Sorry,the number you input must be at least 5"
exit 0
fi
i=5
count=0
while [ $i -le $number ]
do
j=i
while (( $j%5==0 ))
do
let j/=5
let count+=1
done
let i+=1
done
echo "factorial zero is:$count"
|
阅读(671) | 评论(0) | 转发(0) |