View Full Version : Shell script to find whether number is prime or not
preshit.net
20-02-2008, 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
21-02-2008, 09: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
21-02-2008, 01: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!
mehulved
21-02-2008, 04: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
21-02-2008, 04: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.
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.
#!/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
21-02-2008, 06:26 PM
Ya the running time wud be less then.
vBulletin® v3.7.0, Copyright ©2000-2008, Jelsoft Enterprises Ltd.