• 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. CentOS / RHEL 6 : How to configure kdump
  2. ifenslave Command Examples in Linux
  3. CentOS / RHEL : How to view the commands executed in yum history command output
  4. Docker Troubleshooting – “conflict: unable to delete, image is being used by running container”
  5. Defining System Jobs Using Cron under Linux
  6. 3 Ways of Increasing Swap Space on Linux
  7. CentOS / RHEL : How to create and host yum repository over httpd
  8. How to create partitions and file systems on DM-Multipath devices
  9. How to write multiple plays and per-play privilege escalation in Ansible
  10. chattr Command Examples to Change File Attributes (Make files immutable)

You May Also Like

Primary Sidebar

Recent Posts

  • JavaFX ComboBox: Set a value to the combo box
  • Nginx load balancing
  • nginx 504 gateway time-out
  • Images preview with ngx_http_image_filter_module

© 2022 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright