Linux

使用 shell 腳本計算素數

  • November 23, 2021

當數字為素數時,最後一行不執行。請幫忙

#!/bin/bash
echo -e "Enter Number : \c"
read n
while [ $n -gt 2 ]
do
for((i=2; i<=$n/2; i++))
do
 ans=$(( n%i ))
 if [ $ans -eq 0 ]
 then
   echo "$n is not a prime number."
   exit 0
 fi
done
done
echo "$n is a prime number."

新程式碼:

#!/bin/bash
echo -e "Enter Number : \c"
read n
for((i=2; i<=$n/2; i++))
do
 ans=$(( n%i ))
 if [ $ans -eq 0 ]
 then
   echo "$n is not a prime number."
   exit 0
 fi
done
echo "$n is a prime number."

外部 while 循環是無限的:

while [ $n -gt 2 ]

一個工作版本:

#!/bin/bash
echo -e "Enter Number : \c"
read n
for((i=2; i<=$n/2; i++))
do
 ans=$(( n%i ))
 if [ $ans -eq 0 ]
 then
   echo "$n is not a prime number."
   exit 0
 fi
done
echo "$n is a prime number."
#! /bin/bash

read -p "Enter number: " n

d=2
r=1 
while [[ $d -lt $n && $r -ne 0 ]]
do
       r=`expr $n % $d`

       d=`expr $d + 1`
done

if [[ $r -eq 0 ]]
 then
 echo "$n is not a prime number"
else
     echo "$n is a prime number"
fi

引用自:https://unix.stackexchange.com/questions/574079