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
- Take the input from the User
- Check whether the number is greater than 1; if not, then the number is not Prime
- Check if the number gets evenly divided by any number from 2 to half of the number
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Taking the input from User number = int(input("Enter The Number: ")) if number > 1: for i in range(2,int(number/2)): if (number % i == 0): print(number, "is not a Prime Number") break else: print(number,"is a Prime number") # If the number is less than 1 it can't be Prime else: print(number,"is not a 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Enter The Number: 2 2 is a Prime number Enter The Number: 11 11 is a Prime number Enter The Number: 9729262 9729262 is not a Prime Number Enter The Number: -20 -20 is not a Prime number Enter The Number: 1 1 is not a Prime number |
Â
Leave a Comment