Shell script to find whether number is prime or not

Status
Not open for further replies.

preshit.net

ex3n1us m4x1mus
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
 
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

Technomancer
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!
 

mehulved

18 Till I Die............
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

Technomancer
- 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

Journeyman
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
 
Status
Not open for further replies.
Top Bottom