Prime Number Program in Python

Written by

Himani Kohli

In this program, we are going to check whether the given number is prime or not by using python.

Prime number is a positive integer greater than 1 that has no positive integer divisors other than 1 and itself.

In other words, a prime number is a positive integer that is not divisible by any other positive integer except for 1 and itself.

Example-2,3,5,7 etc.

Algorithm:

  • Prompt the user to enter a number.
  • Store the number in a variable n.
  • Check if n is less than or equal to 1. If it is, print The number is not prime and return from the function.
  • Iterate over the range 2 to sqrt(n) (inclusive) using a for loop.
  • Check if n is divisible by the current loop variable. If it is, print The number is not prime and return from the function.
  • Print The number is prime after the for loop has completed.

Code:

n = int(input("Enter the number that has to be checked: "))
a = 0
for i in range(2, int(n / 2)):
    if n % i == 0:  // finding whether the number has a factor or not
        a = a + 1
if a > 0:
    print("The number is not prime")
else:
    print("The number is prime")

Output:

Enter the number that has to be checked:97
The number is prime

Enter the number that has to be checked: 54
The number is not prime
Prime Number Program in Python