2 min read
A prime number is a positive whole number greater than 1 which 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 -
In this article, we will create a Python program to check whether the given number is Prime or not.
Step 1: Take the input from User
Step 2: Check whether the number is greater than 1, if not than the number is not Prime
Step 3: Check if the number gets evenly divided by any number from 2 to half of the number
Step 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.
# Taking the input from User number = int(input("Enter The Number")) if number > 1: for i in range(2,int(number/2)+1): 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")
In the given program first, we are taking the input from the user using the
input keyword and converting it to integer datatype in case the user inputs a Float 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 diving the number to every number between 2 and the half of the number if no factor is found the number is Prime gets printed out along with the number.
Running the program for the following test cases gave us the expected result.
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
Latest from djangocentral