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

• Difficulty Level : Hard
• Last Updated : 30 Sep, 2019

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:

 #storing the number to be checkednumber=43i=2  #flag variablef=0  #running a loop from 2 to number/2while test \$i -le `expr \$number / 2` do  #checking if i is factor of numberif test `expr \$number % \$i` -eq 0 thenf=1fi  #increment the loop variablei=`expr \$i + 1`doneif test \$f -eq 1 thenecho "Not Prime"elseecho "Prime"fi

Output:

Prime
My Personal Notes arrow_drop_up