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 Check If String is Number In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number.Example: Using isdigit() MethodPython# Python code to check if string is numeric
6 min read
Check if a Number is a Whole Number in Python Floating-point numbers in Python can sometimes pose challenges when you need to determine whether they represent whole numbers. Due to the inherent precision limitations of floating-point representation, comparing them directly for equality with integers may lead to unexpected results. In this artic
3 min read
Python | Check Numeric Suffix in String Sometimes, while programming, we can have such a problem in which we need to check if any string is ending with a number i.e it has a numeric suffix. This problem can occur in Web Development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using regex This problem
6 min read
Perfect Number Program in Python A Perfect Number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself.Example:6 is a perfect number because its divisors (excluding itself) are 1, 2, and 3, and their sum is 6 (1 + 2 + 3 = 6).28 is a perfect number because its divisors are 1, 2, 4, 7, 14
3 min read
Python Program to Check Number is a Power of Two we will discuss how to write a Python program to determine whether a given number is a power of two. A number is said to be a power of two if it can be expressed in the form of 2n, where n is a non-negative integer.Examples: Pythondef is_power_of_two(n): if n <= 0: return False return (n & (n
4 min read