# Shell script to find whether number is prime or not



## preshit.net (Feb 20, 2008)

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)

DARK LORD said:


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


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)

DARK LORD said:


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


Where r u getting the problem? Show ur script!


----------



## mehulved (Feb 21, 2008)

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)

- 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 (Feb 21, 2008)

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 (Feb 21, 2008)

Ya the running time wud be less then.


----------

