DIGIT-ARC read-only archive · snapshot: July 23, 2026

Shell script to find whether number is prime or not

7 posts · originally from https://geek.digit.in/community/threads/shell-script-to-find-whether-number-is-prime-or-not.80714/

preshit.net
preshit.net Original post #1
Feb 20, 2008 at 11:26 PM
Okay,

So we've been told to write this shell script to find whether a number taken from user is prime or not.

I know the log, just haven't been able to implement it.

Can anyone help ?

Thanks
MetalheadGautham
Feb 21, 2008 at 9:36 AM
Okay,

So we've been told to write this shell script to find whether a number taken from user is prime or not.

I know the log, just haven't been able to implement it.

Can anyone help ?

Thanks
tried dividing it by all integer numbers till half of itself, and piping the resultant numbers to a log file, and checking the log file for number of lines where the content is just <0> ? If the number is 2, its a prime number.
mediator
Feb 21, 2008 at 1:16 PM
Okay,

So we've been told to write this shell script to find whether a number taken from user is prime or not.

I know the log, just haven't been able to implement it.

Can anyone help ?

Thanks
Where r u getting the problem? Show ur script!
M
Feb 21, 2008 at 4:24 PM
I am able to get it after reading ABS and BGB, but for one problem. 1 is identified as prime. What would be the best method to avoid this?
I can certainly give a simple if statement to check if input is 1, if it is then it will directly print not prime.
Any better way?
mediator
Feb 21, 2008 at 4:39 PM
- count = 0
- for i = 1 to number,
if number % i = 0
count=count+1
- if count <=2, then print => prime

So for 1, count will be 1 and for every other prime it will be 2.
r2d2
r2d2 #6
Feb 21, 2008 at 5:51 PM
OK, converted from one of my earlier c program :)


btw, prime checking can be done upto square root, which will require a little more work.

Code:
#!/bin/sh
 
i=2
rem=1
 
echo -e "Enter a number: \c"
read num
 
if [ $num -lt 2 ]; then
 echo -e "$num is not prime\n"
 exit 0
fi 
 
while [ $i -le `expr $num / 2` -a $rem -ne 0 ]; do
 rem=`expr $num % $i`
 i=`expr $i + 1`
done
 
if [ $rem -ne 0 ]; then
 echo -e "$num is prime\n"
else
 echo -e "$num is not prime\n"
fi
mediator
Feb 21, 2008 at 6:26 PM
Ya the running time wud be less then.