Friday, October 14, 2016

How to check whether a number is prime in UNIX shell script

Dear readers, thanks for your response. The pre-school blog about fabonacci series in unix shell script was a hit! 

Today we will see another script that is asked on a regular basis in various interviews and examinations. We will write a script in UNIX shell scripting to check whether a supplied number is prime or not. But, before we start lets have a look on the basics of prime number.

A number is prime, if it is divisible only by itself and 1.

Thus, to check the primality of a number n, we start dividing the with 2 and continue till n-1
Also, 2 is the only even number which is the smallest prime number. So let get down to wrote the code.


#!/bin/bash
######################################################
# SCRIPT : prime_number.bash
# USAGE  : ./prime_number.bash [Number]
# PURPOSE: Checks whether the given number is prime or not
# AUTHOR : Shashank Rawlani
######################################################


# Test the number of arguements recieved by the script

## Variable declarations
RC=1
ctr=0
num=$1

if [ $# -eq 1 ]; then

        ## Check whether the supplied number is an integer
        expr $num + 1  &> /dev/null

        RC=$?

        while [ $RC -ne 0 ]
        do

                echo "Sorry, you have supplied a non numerical value"
                echo ""
                echo -n "Enter a number: "
                read num

                ctr=`expr $ctr + 1`

               expr $num + 1  &> /dev/null
                RC=$?

                if [ $RC -ne 0 && $ctr -eq 5 ]; then
                        echo "Maximum tries reached"
                        exit 1;
                fi

        done


fi

## Actual primality test starts here 
i=2

while [ $i -lt $num ]
do
  if [ `expr $num % $i` -eq 0 ]
  then
      echo "$num is not a prime number"
      echo "Since it is divisible by $i"
      exit
  fi
  i=`expr $i + 1`
done


echo "$num is a prime number "



You can also find the script on www.rawlani.com.
Do let me know your comments below or write me on shashank@rawlani.com.

0 comments:

Post a Comment