Open In App

Python Program to Check Prime Number

Last Updated : 05 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

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.

NOte: Negative numbers (e.g. -13) are not considered prime number.

# importing sympy module
from sympy import *

# calling isprime function on different numbers
geek1 = isprime(30)
geek2 = isprime(13)
geek3 = isprime(2)

print(geek1) 
print(geek2) 
print(geek3) 

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. 

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 ( i.e. checking till √n )

from math import sqrt
# n is the number to be check whether it is prime or not
n = 1

# this flag maintains status whether the n is prime or not
prime_flag = 0

if(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

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 prime_flag 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 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.

from math import sqrt

# prime function to check given number prime or not
def Prime(number, itr):  
    # base condition
    if itr == 1 or itr == 2:  
        return True
      # if given number divided by itr or not
    if number % itr == 0:  
        return False
      # Recursive function Call
    if Prime(number, itr - 1) == False:  
        return False

    return True

num = 13

itr = int(sqrt(num) + 1)

print(Prime(num, itr))

Output
True

Explanation:

  • This code defines a recursive function Prime() to check if a number number is prime.
  • Base condition: The recursion ends when the iterator itr reaches 1 or 2, returning True because numbers 1 and 2 are prime.
  • Divisibility check: If number is divisible by itr (i.e., number % itr == 0), it returns False (meaning number is not prime).
  • Recursive Call: The function calls itself with itr – 1, effectively checking for divisibility from itr down to 2.
  • If the function finds no divisors by the time itr reaches 2, it returns True (indicating the number is prime).

Using Trial Division Method

First, check if the number is less than or equal to 1, and if it is, return False. Then, loop through all numbers from 2 to the square root of the given number (rounded down to the nearest integer). If the number is divisible by any of these values, return False. Otherwise, return True.

n = 11

if n <= 1:
    print(False)
else:
    is_prime = True
    for i in range(2, int(n**0.5) + 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 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.

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.

Recommended Artilce – Analysis of Different Methods to find Prime Number in Python

Python Program to Check Prime Number – FAQs

How to find prime numbers in a range in Python?

You can find prime numbers in a range using a function to check for primality and then iterating through the range to collect prime numbers.

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

def prime_numbers_in_range(start, end):
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes

print(prime_numbers_in_range(10, 50)) # Output: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

How to add prime numbers in Python?

You can sum prime numbers by using a similar approach to finding primes and then summing the resulting list.

def sum_of_primes(start, end):
primes = prime_numbers_in_range(start, end)
return sum(primes)

print(sum_of_primes(10, 50)) # Output: 328

How to find prime factors in Python?

You can find the prime factors of a number by dividing the number by the smallest possible prime and continuing with the quotient.

def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors

print(prime_factors(56)) # Output: [2, 2, 2, 7]

How to find the prime number list in Python?

To find a list of prime numbers up to a given number, you can use the Sieve of Eratosthenes algorithm.

def sieve_of_eratosthenes(limit):
is_prime = [True] * (limit + 1)
p = 2
while p * p <= limit:
if is_prime[p]:
for i in range(p * p, limit + 1, p):
is_prime[i] = False
p += 1
primes = [p for p in range(2, limit + 1) if is_prime[p]]
return primes

print(sieve_of_eratosthenes(50)) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Is there a formula to find prime numbers?

There is no simple formula to generate prime numbers. However, various algorithms, such as the Sieve of Eratosthenes, can efficiently find all prime numbers up to a certain limit. Formulas and methods like Wilson’s theorem can help check the primality of a given number but are not practical for generating prime numbers.



Next Article

Similar Reads

three90RightbarBannerImg