linux - Bash 脚本,按顺序列出数字 1-1000,概率为黄色,偶数为绿色,素数为蓝色

标签 linux bash shell scripting primes

显然这是一个类作业。我已经玩了几天了。我很容易让奇数和偶数方面工作得很好,但我一直遇到质数方面的问题。

这是奇数/偶数并且有效

  #!/bin/bash
  for i in $(seq 1000)
  do
    if (($i % 2));then  #even
        echo -e "\e[32m$i\e[0m"  #green

    else  #odd
        echo -e "\e[33m$i\e[0m"  #yellow

    fi
  done

这是针对奇数/偶数/素数的,我无法让它工作。

  #!/bin/bash
  for i in $(seq 1000)
  do
    if (($i % 2));then  #even
            if
                    ($i -eq factor {2..1000})
                            echo -e "\e[34m$i\e[0m" #blue
            else
                    echo -e "\e[32m$i\e[0m"  #green
            fi
    else  #odd
            if
                    ($i -eq factor {2..1000})
                            echo -e "\e[34m$i\e[0m" #blue
            else
                    echo -e "\e[33m$i\e[0m"  #yellow
            fi
    fi
  done

这只是我最近的尝试。我尝试了几种不同的方法,但没有用。一点帮助将不胜感激。也许我做的完全错了,也许我很接近,但我花了很多时间研究它,但似乎永远无法将它应用到我的脚本中。

最佳答案

使用 factor 确定数字是否为质数的基本方法是可行的,但需要做一些工作来提取信息。这个原始代码的修改版本是一种方法:

#!/bin/bash

# A glob pattern to match 'factor' output that has at least two numbers
# separated by whitespace after a colon (e.g. '30: 2 3 5')
composite_factors_glob='*:*[0-9]*[[:space:]]*[0-9]*'

for i in {1..1000} ; do
    factors=$(factor "$i")
    # shellcheck disable=SC2053
    if (( i > 1 )) && [[ $factors != $composite_factors_glob ]] ; then
        echo -e "\e[34m$i\e[0m" # prime => blue
    elif ((i%2 == 0)) ; then
        echo -e "\e[32m$i\e[0m" # even  => green
    else
        echo -e "\e[33m$i\e[0m" # odd   => yellow
    fi
done

#shellcheck 注释抑制了虚假的 Shellcheck警告。

关于linux - Bash 脚本,按顺序列出数字 1-1000,概率为黄色,偶数为绿色,素数为蓝色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603320/

相关文章:

linux - 解析大括号中的 block

linux - 如何使g++正确使用我自己的glibc构建的 header ?

json - 为什么我的 jq 在 JSON 上失败?

linux - 使用 While 和 IF 进行验证

linux - 如何用 shell 脚本替换文本文件中的特定行?

mysql - bash循环mysql输出多个变量

java - 在 Linux 上将 .jar 应用程序作为守护进程运行的原因

linux - 在 Linux 的脚本环境中解密变量

bash - 为 SSH 生成子 shell 并继续程序流程

shell - 在 Debian/Ubuntu 上出现 `apt install -y iptables persistent` 时阻止提示