gpt4 book ai didi

python - Shell 脚本主要文本

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:20 24 4
gpt4 key购买 nike

我正在尝试从 Python ( What is the best algorithm for checking if a number is prime? ) “转换”为 Shell 脚本。这是我的想法(可能是非常愚蠢的代码):

#!/bin/bash
prime (){
i=5
w=2
while [ `echo "$i*$i" | bc -l ` -le $n ]
do
if [ n % i -eq 0 ]
then echo "$n is not prime"
else
i = i + w
w = 6 - w
echo "$n is prime"
fi
done
}
echo "Test for knowing if a number is prime or not."
sleep 2
echo "Enter the number"
read n
if [ $n -eq 1 ]
then echo "Number 1 is not prime"
elif [ $n -eq 2 ]
then echo "Number two is prime"
elif [ $n -eq 3 ]
then echo "Number three is prime"
else
prime
fi

问题是当我输入任何其他数字(4、5、6...)时,无论 $n 是否为素数,程序都不会返回。如果有人能帮助我,我将非常感激。

最佳答案

如果您可以从 GNU 核心实用程序访问 factor:

f=$(factor 11 | wc -w); [[ $f -eq 2 ]] && echo prime || echo not prime

输出:

prime

f=$(factor 6 | wc -w); [[ $f -eq 2 ]] && echo prime || echo not prime

输出:

not prime

关于python - Shell 脚本主要文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com