Bash program to check if the Number is a Prime or not

Given a number, the task is to find whether the given number is prime or not using Bash Scripting.

Examples:

Input: N = 43
Output: Prime

Input: N = 35
Output: Not Prime

Prime Numbers:
A prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 …..

Approach:
We run a loop from 2 to number/2 and check if there is any factor of the number. If we find any factor then the number is composite otherwise prime.

Implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

#storing the number to be checked
number=43
i=2
  
#flag variable
f=0
  
#running a loop from 2 to number/2
while test $i -le `expr $number / 2` 
do
  
#checking if i is factor of number
if test `expr $number % $i` -eq
then
f=1
fi
  
#increament the loop variable
i=`expr $i + 1`
done
if test $f -eq
then
echo "Not Prime"
else
echo "Prime"
fi

chevron_right


Output:

Prime


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.