本文介绍了检查数字是否是bash中的质数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写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

 #!/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

推荐答案

使用 factor 很容易.但是,如果您以某种方式需要脚本,则可以实现类似以下的操作.我不确定这是否是最好的算法,但是这比您的算法有效.

Using factor would be easy. 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

这篇关于检查数字是否是bash中的质数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:44
查看更多