bash 质数脚本检查器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39002533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prime Number Script Checker
提问by Randy Teer
I am new to scripting. The script below checks if a number inputted is a prime number or divisible by 2. Why is the third line from the bottom needed (i=expr $i + 1
). I commented that line out to see what the script would do and it hangs the script up. Please advise.
我是脚本新手。下面的脚本检查输入的数字是否为质数或可被 2 整除。为什么需要从底部算起的第三行 (i= expr $i + 1
)。我注释掉了那行,看看脚本会做什么,它会挂起脚本。请指教。
#! /bin/bash
echo -n "Enter a number: "
read num
i=2
while [ $i -lt $num ]
do
if [ `expr $num % $i` -eq 0 ]
then
echo "$num is not a prime number"
echo "Since it is divisible by $i"
exit
fi
i=`expr $i + 1`
done
echo "$num is a prime number "
回答by chepner
If you don't increment i
, then the test [ $i -lt $num ]
will never be false, assuming i
starts out less than num
.
如果您不增加i
,则[ $i -lt $num ]
假设i
开始时小于,则测试永远不会为假num
。