Open In App

Check Prime Number in Python

Last Updated : 10 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
True

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")

Output
True

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)

Output
False
True

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))

Output
True

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


Next Article

Similar Reads