Given a positive integer n, the task is to check whether the number is prime or not in Python. A prime number is a number greater than 1 that has exactly two factors, 1 and itself. For Example:
Input: n = 29
Output: Prime NumberInput: n = 10
Output: Not a Prime Number
Let’s look at the methods below to check for a prime number.
Using flag variable
The program checks whether the number is divisible by any value from 2 to √n. If any divisor is found, the number is not prime; otherwise, it is prime.
n = 11
if n <= 1:
print(False)
else:
prime = True
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
prime = False
break
print(prime)
Output
True
Explanation:
- n <= 1 checks numbers that are not prime. Loop runs from 2 to √n.
- n % i == 0 checks divisibility and prime becomes False if a divisor is found.
Using isprime() method
This method uses the isprime() function from the SymPy library to check whether a number is prime.
from sympy import isprime
n = 13
print(isprime(n))
Output
True
Explanation:
- isprime(n) checks whether n is prime.
- Function returns True for prime numbers and False otherwise.
Using Sieve of Eratosthenes
This method creates a list of numbers and marks multiples of each number as non-prime until the target number is reached.
def is_prime(n):
if n < 2:
return False
s = [True] * (n + 1)
s[0] = s[1] = False
for i in range(2, int(n**0.5) + 1):
if s[i]:
for j in range(i * i, n + 1, i):
s[j] = False
return s[n]
print(is_prime(31))
Output
True
Explanation:
- s stores prime status of numbers.
- Multiples of each number are marked False.
- s[n] determines whether the number is prime.
Using Recursion
This approach checks divisibility recursively by reducing the divisor value in each function call.
from math import sqrt
def prime(n, i):
if i == 1:
return True
if n % i == 0:
return False
return prime(n, i - 1)
n = 13
print(prime(n, int(sqrt(n))))
Output
True
Explanation:
- Function checks whether n is divisible by i. If divisible, it returns False.
- Otherwise, recursion continues with i - 1. If no divisor is found, it returns True.