07 October 2011

Finding Prime Number using Shell Script in Linux/Unix

7 comments

Q. How do I find prime number using Shell Script


Ans:

#!/bin/bash
prime_1=0
echo "enter the range"
read n
echo " Primenumber between 1 to $n is:"
echo "1"  
echo "2"
for((i=3;i<=n;))
do
for((j=i-1;j>=2;))
do
if [  `expr $i % $j` -ne 0 ] ; then
prime_1=1
else
prime_1=0
break
fi
j=`expr $j - 1`
done
if [ $prime_1 -eq 1 ] ; then
echo $i
fi
i=`expr $i + 1`
done


Output


finding prime number in bash


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

7 comments:

  1. pls provide the comments of the program

    ReplyDelete
  2. i need the commnets for each line of the program

    ReplyDelete
  3. Write a Shell Script to find first n prime numbes

    ReplyDelete
  4. This version works way quicker by only dividing by previous found primes:

    echo -n "1 "; echo -n "2 "; k=1000; h[$k]=2; for((i=3;i<=1000;i++)); do for j in ${h[@]}; do if [ ! "$j" == "" ]; then if [ `expr $i % $j` -ne 0 ] ; then prime_1=1; else prime_1=0; break; fi; fi; done; if [ $prime_1 -eq 1 ] ; then echo -n "$i "; ((k=$k-1)); h[$k]=$i; fi; done; echo

    ReplyDelete
    Replies
    1. Even faster..

      unset h; echo -n "1 "; echo -n "2 "; k=0; h[$k]=2; for((i=3;i<=1000;i++)); do for j in ${h[@]}; do if [ ! "$j" == "" ]; then if [ `expr $i % $j` -ne 0 ] ; then prime_1=1; else prime_1=0; break; fi; fi; done; if [ $prime_1 -eq 1 ] ; then echo -n "$i "; ((k++)); h[$k]=$i; fi; done; echo

      Delete