How to Check if a Number is Prime in Python
The fastest way to check if a number is prime in Python is dividing only up to its square root:
import math
def es_primo(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
When do you need this?
A prime number is only divisible by 1 and by itself. Checking primes is a classic exercise in Python and a common question in technical interviews. You will also find it in cryptography, random number generation and math exercises. In this guide you will learn how to check if a number is prime in Python, from a simple loop to an optimized algorithm.
Method 1: Check with a simple loop
The most direct way is to try dividing the number by every value from 2 to n - 1.
def es_primo(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
print(es_primo(7)) # True
print(es_primo(10)) # False
Method 2: Optimize with the square root (recommended)
You only need to check divisors up to the square root of n. If none of them divides n, the number is prime. This makes the function much faster.
import math
def es_primo(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
Method 3: Optimize with the 6k ± 1 rule
For large numbers you can skip even numbers and multiples of 3. Every prime greater than 3 has the form 6k - 1 or 6k + 1.
def es_primo(n):
if n < 2:
return False
if n in (2, 3):
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
Method comparison
| Method | Advantage | When to use it |
|---|---|---|
| Simple loop | Easy to understand | Learning and small numbers |
| Square root | Fast for most cases | Recommended in general |
| 6k ± 1 rule | Very fast | Large numbers and contests |
Special cases and common errors
Remember to handle the special cases before anything else:
- Numbers less than 2 are not prime.
2is the only even prime number.0and1are not prime.
print(es_primo(1)) # False
print(es_primo(2)) # True
print(es_primo(0)) # False
Frequently asked questions
Is 1 a prime number?
No. A prime number must be greater than 1.
Is 2 a prime number?
Yes. 2 is the smallest prime number and the only even prime.
What is the fastest way to check primality in Python?
For most cases, the square root optimization is enough. For very large numbers you can use the 6k ± 1 rule or specialized libraries.
Related content
- How to Remove Duplicates from a List in Python
- How to Convert String to Int in Python
- Python How-To Tutorials
- Python Course from Scratch
Related keywords
how to check if a number is prime in python, prime number python, is prime python, numero primo python, check prime python, prime number algorithm python, math sqrt python
Save this tutorial and share it if it helped you. Find more practical guides in the Python how-to section.