Wednesday, 15 October 2014

How to write a bash script to find prime numbers within a range.

Prime number is not the actual goal of this program, the actual goal is to show how nested loop works in bash script. I am giving the program below and will describe the logic of the program.

#!/bin/bash
#Author: Subhroneel Ganguly
#Date: 15.10.2014

echo Enter Range:
# Read user input and store into RANGE variable
read RANGE
# Initialize NUM to 1
NUM=1
#looping NUM from 1 to RANGE and each number will be checked for prime.
while [ "$NUM" -le "$RANGE" ]
        do
# variable I is the divisor to test for prime number
        I=2
# variable FLAG will indicate whether a number is prime or not.
        FLAG=0
# condition is checked if NUM less than to we will do nothing and value of FLAG will be 0 and hence number will be non prime.
        if [ "$NUM" -gt 2 ]
        then
                while [ "$I" -lt "$NUM" ]
                do
# % returns modulus, if number gives 0 remainder then it is divisible by the number and hence non prime. Notice we have started I from 2 and will run until NUM-1
                        if [ $(($NUM%$I)) -eq 0 ]
                        then
                                flag=1
                        fi
                        let I+=1
                done
        else
                FLAG=1
        fi
        if [ "$FLAG" -eq 1 ]
        then
                echo $NUM is not prime
        else
                echo $NUM is prime
        fi
        let NUM+=1
done

You can also watch this tutorial in YouTube with the following link : https://www.youtube.com/watch?v=LkLH6FgRmtw

 Press like if you like the video and you can also subscribe to my channel : My Youtube Channel

No comments: