• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

Shell/Bash Script to Find Prime Numbers in Linux

by admin

A prime number is a whole number that has exactly 2 different factors, 1 and itself. A number that is not a prime number will be called composite. Except 1 each natural number that is divisible by only 1 and itself is called a prime number. For example: 2,3,5,7,11,13,17,19,23,29… etc.

  • There are total 25 prime number upto 100 and 46 prime numbers upto 200.
  • 2 is the only prime number and the smallest prime number, rest all prime numbers are odd.
  • 1 is neither prime not composite number.

Bash Script to Find Prime number is a given Range of Numbers

1. Configure the script as shown below in /tmp/prime_num.sh file:

#!/bin/bash

prime_1=0
echo "enter the range"
read n
echo " Prime number 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

2. Assign executible permissions to the file before running it:

$ chmod +x /tmp/prime_num.sh

3. Run the script as shown below and provide a range (for example 50 to find prime numbers between 0 to 50).

find prime number using shell script

Filed Under: DevOps, Linux, Shell Scripting

Some more articles you might also be interested in …

  1. avahi-browse Command Examples in Linux
  2. Linux OS Service ‘avahi-daemon’
  3. How to configure resource groups for MySQL Server running on Linux
  4. How does “chmod -R 755” works
  5. test: command not found
  6. eject: command not found
  7. KVM Virsh Command Examples on CentOS and RHEL
  8. chronyc : command not found
  9. autopkgtest: command not found
  10. CentOS / RHEL 7 : systemd-analyze command to find booting time delays

You May Also Like

Primary Sidebar

Recent Posts

  • nixos-rebuild Command Examples in Linux
  • nixos-option: Command Examples in Linux
  • nixos-container : Command Examples in Linux
  • nitrogen Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright