Prime Factors Using Bash Script
To do solve this problem we use the factor command available in the shell. The factor command prints the print the prime factors of the given number. The command executes as follows.
$ factor 6 6: 3 2 $ factor 5 5: 5
From the above example we can clearly see that factor n return the all prime factors of n. If the given number ‘n’ is a prime number the number of factor will be one i.e. the number itself. If the given number ‘n’ is a non prime number then the number of factor is greater than 1.
Now, we need to evaluate the factor command for each input in a to b where a is the lower range and b is the upper range given by the user. If factor i return exactly 2 arguments we will conclude that I is a prime number otherwise I is a non prime number.
For this we need to set the output of factor command to command line using set command then using the $# variable we will determine the number of values in the command line.
Code
# Unix Shell Script To Print Prime Numbers In A Given Range [a, b] if [ $# -ne 2 ] then echo "Wrong Number Of Arguments" exit fi if [ $2 -lt 0 -o $1 -lt 0 ] then echo "Argument One Or Two Is Negative." exit fi a=$1 b=$2 if [ $a -gt $b ] then t=$a a=$b b=$t fi echo "Prime Numbers In Range [$a, $b] Are:" echo -ne "[" for i in `seq $a 1 $b` do set -- `factor $i` if [ $# -eq 2 ] then echo -ne "$i," fi done echo -e "\b]"
Output
$sh primerange.sh 1 10 Prime Numbers In Range [1, 10] Are: [2,3,5,7] $sh primerange.sh 10 50 Prime Numbers In Range [10, 50] Are: [11,13,17,19,23,29,31,37,41,43,47] $sh primerange.sh Wrong Number Of Arguments $sh primerange.sh -5 10 Argument One Or Two Is Negative.