In this article, we will create a Python program to check prime number. Before we get started, if you want to Data Type in Python, please go through the following article: Data Types in Python.

A prime number is a positive whole number greater than 1 that is evenly divisible only by 1 and itself. 2, 3, 5, 7, 11, 13 are the first few prime numbers. Some interesting facts about Prime numbers –

  • 2 is the only even prime number
  • 0 and 1 are not considered prime numbers
  • Numbers that have more than two factors are called composite numbers.
  • No prime number greater than 5 ends in a 5. Any number greater than 5 that ends in a 5 can be divided by 5.

Algorithm To Check Check Prime Number

  1. Take the input from the User
  2. Check whether the number is greater than 1; if not, then the number is not Prime
  3. Check if the number gets evenly divided by any number from 2 to half of the number
  4. Print the result

Here we have optimized the algorithm to search only till half of the given number, which drastically improves the performance for a very large number.

Python Program to Check Prime Number

Explanation

In the given program, first, we are taking the input from the user using the input keyword and converting it to an integer datatype in case the user inputs a floating number. Next, we are comparing if the number is less than 1 because only a number greater than 1 can be called a Prime number.

Inside the loop, we are dividing the number by every number between 2 and half of the number If no factor is found, the number is Prime and gets printed out along with the number. Running the program for the following test cases gave us the expected result.

 

Leave a Comment