Sunday, March 16, 2014

Check if the number is prime – Linux Shell Script

Problem Question


Write a script to check whether the given number is prime or not

Explanation of Problem


Here we wish to write a Linux Shell Script that would take a command line argument and check if that number is prime or not and print the result (PRIME or NOT PRIME) on the terminal.

Code



#*Check Prime*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 16-03-2014
x=`expr $1 / 2`
i=2
while [ $i -le $x ]
 do
  if [ `expr $1 % $i` -eq 0 ]
   then
    echo Not Prime
    exit
  fi
  i=`expr $i + 1`
 done
echo Prime

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

x=`expr $1 / 2` -> We declare a variable ‘x’ and assign it a value which is equal to half that of the first command line argument. This will help us know where to stop our loop which will divide the number with every integer until it finds the remainder of the division to be zero. Thus we can limit the loop counter to half the value of the number to be checked. Thus we use while [ $i -le $x ] as our loop.

i=2 -> This is our loop counter. We start at 2 since every number is divisible by 1.

if [ `expr $1 % $i` -eq 0 ] -> As soon as we find the remainder of the division is zero, we use echo Not Prime to display Not Prime on the terminal, and with the exit command we close our shell running the script, i.e., the script terminates.

i=`expr $i + 1` -> Loop counter incremented by one.

echo Prime -> If the control reaches here, it means that the number is not prime since it was not divisible by any of the numbers (upto half the number itself). Thus, we print Prime on the terminal.

then fi -> if block delimiters.

do done -> while block delimiters.

Output(s)



1 comment:

Need help?