简体   繁体   English

检查数字是否是bash中的质数

[英]check if a number is a prime in bash

I am trying to write a bash script to find if a number is prime, but i can't find what is wrong with my script 我正在尝试编写bash脚本以查找数字是否为质数,但是我找不到脚本有什么问题

 #!/bin/bash

    #set -x
    echo -n "enter a number " 
    read isPrime
    count=2
    x=0 
    while [ $count -lt $isPrime ]; do 
        if [ `expr $isPrime % $count`-eq 0 ]; then
        echo "not prime"
         fi
        count=`expr $count + 1`

    done

    echo " it is prime"

    #set +x

Using factor would be easy. 使用factor将很容易。 But if you somehow need a script, I would implement something like following. 但是,如果您以某种方式需要脚本,则可以实现类似以下的操作。 I'm not sure whether this is the best algorithm, but this is way efficient than yours. 我不确定这是否是最好的算法,但是这比您的算法有效。

function is_prime(){
    if [[ $1 -eq 2 ]] || [[ $1 -eq 3 ]]; then
        return 1  # prime
    fi
    if [[ $(($1 % 2)) -eq 0 ]] || [[ $(($1 % 3)) -eq 0 ]]; then
        return 0  # not a prime
    fi
    i=5; w=2
    while [[ $((i * i)) -le $1 ]]; do
        if [[ $(($1 % i)) -eq 0 ]]; then
            return 0  # not a prime
        fi
        i=$((i + w))
        w=$((6 - w))
    done
    return 1  # prime
}

# sample usage
is_prime 7
if [[ $? -eq 0 ]]; then
  echo "not a prime"
else
  echo "it's a prime"
fi

You can find an explanation about the used algorithm here 您可以在此处找到有关所用算法的说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM