Check Prime Number in Python
Last Updated :
10 Apr, 2025
Given a positive integer N, the task is to write a Python program to check if the number is Prime or not in Python. For example, given a number 29, it has no divisors other than 1 and 29 itself. Hence, it is a prime number.
Note: Negative numbers (e.g. -13) are not considered prime number.
Using sympy.isprime() method
In the sympy module, we can test whether a given number n is prime or not using sympy.isprime() function. For n < 264 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. Before using sympy module, we need to install it using this command:
pip install sympy
Python
from sympy import *
g1 = isprime(30)
g2 = isprime(13)
g3 = isprime(2)
print(g1)
print(g2)
print(g3)
Output
False
True
True
Explanation:
- isprime() function from the SymPy library checks if a number is prime or not.
- It prints False for 30, True for 13 and True for 2 because 30 is not prime, while 13 and 2 are prime numbers.
Using Math Module
The code implements a basic approach to check if a number is prime or not, by traversing all the numbers from 2 to sqrt(n)+1 and checking if n is divisible by any of those numbers.
Python
import math
n = 11
if n <= 1:
print(False)
else:
is_prime = True
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
is_prime = False
break
print(is_prime)
Explanation:
- Check if n <= 1, if true, it's not prime.
- Loop from 2 to the square root of n, if n % i == 0, it's not prime. If no divisors found, n is prime.
Using Flag Variable
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
Python
from math import sqrt
n = 17
p_fl = 0
if(n > 1):
for i in range(2, int(sqrt(n)) + 1):
if (n % i == 0):
p_fl = 1
break
if (p_fl == 0):
print("True")
else:
print("False")
else:
print("False")
Explanation:
- If n is greater than 1, it loops from 2 to the square root of n to check if any number divides n evenly.
- If any divisor is found, the p_fl is set to 1, indicating n is not prime. If no divisors are found, it prints "True" (meaning n is prime). Otherwise, it prints "False".
- If n <= 1, it directly prints "False" since numbers less than or equal to 1 are not prime.
Using Miller-Rabin Primality Test
We can use the Miller-Rabin Primality Test, a probabilistic method, to check if a number is prime by performing multiple rounds of testing, where each test verifies if a randomly chosen base witnesses the compositeness of the number.
Python
import random
n = 30
k = 5
if n <= 1:
print(False)
elif n <= 3:
print(True)
elif n % 2 == 0:
print(False)
else:
d = n - 1
while d % 2 == 0:
d //= 2
is_prime = True
for _ in range(k):
a = random.randint(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
while d != n - 1:
x = (x * x) % n
d *= 2
if x == 1:
is_prime = False
break
if x == n - 1:
break
if not is_prime:
break
print(is_prime)
n = 3
k = 5
if n <= 1:
print(False)
elif n <= 3:
print(True)
elif n % 2 == 0:
print(False)
else:
d = n - 1
while d % 2 == 0:
d //= 2
is_prime = True
for _ in range(k):
a = random.randint(2, n - 2)
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
while d != n - 1:
x = (x * x) % n
d *= 2
if x == 1:
is_prime = False
break
if x == n - 1:
break
if not is_prime:
break
print(is_prime)
Explanation:
- Return False if n <= 1 or even, True if n <= 3.
- Set d = n-1 and repeatedly divide by 2. Perform k iterations, picking a random base a and checking x = a^d % n.
- If any test fails, return False; else, return True.
Using Recursion
We can also find the number prime or not using recursion. We can use the exact logic shown in method 2 but in a recursive way.
Python
from math import sqrt
def Prime(n, i):
if i == 1 or i == 2:
return True
if n % i == 0:
return False
if Prime(n, i - 1) == False:
return False
return True
n = 13
i = int(sqrt(n) + 1)
print(Prime(n, i))
Explanation:
- Base condition: The recursion ends when the iterator i reaches 1 or 2, returning True because numbers 1 and 2 are prime.
- Divisibility check: If n is divisible by i (i.e., n % i == 0), it returns False (meaning n is not prime).
- Recursive call: The function calls itself with i - 1, checking for divisibility from i down to 2.
- If the function finds no divisors by the time i reaches 2, it returns True, indicating the number is prime.
Recommended Artilce – Analysis of Different Methods to find Prime Number in Python
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read