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

编程入门 行业动态 更新时间:2024-10-25 06:28:07
本文介绍了检查数字是否是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中的质数

本文发布于:2023-11-29 22:50:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:质数   数字   bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!