pysnippets.numbers.is_prime
Check if a number is prime
is_prime(n: int) -> bool
Test primality by trial division up to the integer square root.
Fine up to about 10¹². For bigger numbers, use a probabilistic test like Miller–Rabin.
is_prime.py✓ ruff · mypy --strict
from math import isqrt
def is_prime(n: int) -> bool:
"""Return ``True`` if ``n`` is a prime number."""
if n < 2:
return False
if n < 4:
return True
if n % 2 == 0:
return False
return all(n % d for d in range(3, isqrt(n) + 1, 2))- isqrt is exact; int(sqrt(n)) can be off by one for huge n
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> is_prime(11)Truepassed on Python 3.11 to 3.14: >>> [n for n in range(20) if is_prime(n)][2, 3, 5, 7, 11, 13, 17, 19]passed on Python 3.11 to 3.14: >>> is_prime(-7)FalseEdit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
- Numbers below 2 aren’t prime; 2 and 3 are.
- Even numbers are ruled out once, then only odd divisors are tried.
- A divisor above √n would pair with one below it, so the search stops at
isqrt(n).
Complexity: O(√n) time, O(1) space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.numbers.is_prime import is_primeNo dependencies: copy is_prime.py into your project, or clone the repo.Adapted from is-prime in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Uses math.isqrt, which stays exact for huge n where int(sqrt(n)) rounds; typed. Suggest an edit.