0

Last line is not executing when the number is prime. Please help

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

The new code:

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

3 Answers 3

4

The outer while loop is infinite:

while [ $n -gt 2 ]

A working version:

#!/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."
11
  • But last line is not executing I tried with 13. Commented Mar 21, 2020 at 14:39
  • @AnkitKumar Works for me. Commented Mar 21, 2020 at 14:43
  • The cursor keeps on blinking and does not show the number is prime . I'm using ubuntu 18 Commented Mar 21, 2020 at 14:51
  • @AnkitKumar show the new code in https://pastebin.com/. Commented Mar 21, 2020 at 15:01
  • 1
    @guillermochamorro no, please don't. The new code should be added to the question. Commented Mar 21, 2020 at 15:19
0
#! /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
0
#!/bin/bash

read j
 i=2
while (($i<$j))
do
   f=((j%i))
if [ $f -eq 0] && [ $j -ne $i ]
then
   # echo "is a not prime number"
  i=$i+$j
elif [ $f -ne 0 ]
then
   ((i++))
else [ $j -ne $i ]
then
echo "is a prime number"
fi
done

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.