Python program to check whether a number is Prime or not
Given a positive integer N, The task is to write a Python program to check if the number is Prime or not in Python.
Examples:
Input: n = 11 Output: True Input: n = 1 Output: False
What is the Prime number
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.
Prime Number Program in Python
Method 1:
The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2) using a for loop and for every number check if it divides N. If we find any number that divides, we return false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime and we will return True.
Python3
num = 11# If given number is greater than 1if num > 1: # Iterate from 2 to n / 2 for i in range(2, int(num/2)+1): # If num is divisible by any number between # 2 and n / 2, it is not prime if (num % i) == 0: print(num, "is not a prime number") break else: print(num, "is a prime number")else: print(num, "is not a prime number") |
Output
11 is a prime number
Method 2: Fastest Algorithm to Find Prime Numbers
Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of a smaller factor that has been already checked. Now let’s see the code for the first optimization method ( i.e. checking till √n )
Python3
from math import sqrt# n is the number to be check whether it is prime or notn = 1# this flag maintains status whether the n is prime or notprime_flag = 0if(n > 1): for i in range(2, int(sqrt(n)) + 1): if (n % i == 0): prime_flag = 1 break if (prime_flag == 0): print("True") else: print("False")else: print("False") |
Output:
False
RECOMMENDED ARTICLE – Analysis of Different Methods to find Prime Number in Python


