Coding

How to Check if a Number Is Prime in Python (With Code)

To check if a number is prime in Python, reject anything below 2, then test whether any integer from 2 up to the integer square root of the number divides it evenly. If none does, the number is prime.

from math import isqrt

def is_prime(n: int) -> bool:
    if n < 2:
        return False
    if n % 2 == 0:
        return n == 2
    for divisor in range(3, isqrt(n) + 1, 2):
        if n % divisor == 0:
            return False
    return True

Example use and output:

>>> [n for n in range(50) if is_prime(n)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> is_prime(97)
True
>>> is_prime(91)
False

The rest of this article explains why each line is there, which mistakes produce wrong answers, and what to use when the numbers get large. math.isqrt has been in the standard library since Python 3.8, so this code needs no installs on any supported version.

What "prime" means, and the edge cases that break most code

A prime is a whole number greater than 1 whose only positive divisors are 1 and itself. That definition produces four edge cases that a correct function has to handle on purpose:

  • 0 and 1 are not prime. The number 1 has a single divisor, itself. The guard n < 2 catches both.
  • Negative numbers are not prime. The same guard returns False for them. SymPy's documentation says the same: negative numbers such as -2 are not considered prime.
  • 2 is prime, and it is the only even prime. That is why the code handles even numbers separately: any other even number is divisible by 2, so it is composite.
  • Squares of primes are composite. 25 is 5 times 5. The loop must include the square root itself, which is why the range ends at isqrt(n) + 1.

The last point is the classic off-by-one. Python's range(3, limit) stops before limit. If you wrote range(3, isqrt(n)), then for 25 the loop would test only 3, never reach 5, and report that 25 is prime. Adding 1 makes the upper bound inclusive.

How the trial-division check works

Trial division means trying possible divisors one at a time. You do not need to try all of them, only the ones up to the square root of n. The reason is arithmetic: if n = a * b and both a and b were greater than the square root of n, then a * b would be greater than n. So every composite number has a divisor that is at most its square root. If the loop finds nothing by then, no divisor exists.

Take 91. Its integer square root is 9, so the loop tests 3, 5, 7 and 9. The division 91 % 7 gives 0, so the function returns False at 7. Indeed 91 is 7 times 13, which looks prime at a glance and is a common trap. Now take 97. Its integer square root is 9 as well. The loop tests 3, 5, 7 and 9, none divides 97, and the function returns True.

The modulo operator % returns the remainder of a division, and a remainder of 0 means the divisor goes in evenly. If you want a refresher on how % and // behave, see Python operators explained.

Why use math.isqrt instead of math.sqrt

The Python documentation defines isqrt(n) as the integer square root of a nonnegative integer n: the floor of the exact square root, or equivalently the greatest integer a such that a * a <= n. It takes and returns integers.

The older idiom is int(math.sqrt(n)). It works for small numbers, but math.sqrt returns a float, and a float cannot represent every large integer exactly. For a big n the float result can land slightly above or below the true value, and after int() your loop can stop one step early or late. isqrt avoids that because it never leaves integer arithmetic. It is also shorter to read, since the intent (a whole-number limit) is in the name.

Why the loop skips even numbers

After the check for 2, every even divisor is pointless: if an even number divided n, then 2 would divide n too, and the earlier check would already have returned. So the loop starts at 3 and uses a step of 2 (range(3, limit, 2)), visiting only odd candidates. That halves the work.

For a concrete size, take 2147483647, which is 2**31 - 1 and a known prime. Its integer square root is 46340. The odd candidates from 3 to 46339 number 23,169, so the function makes at most that many modulo operations before answering True. That is quick for a single number, but the cost grows with the square root of n, so a number with 30 digits would need on the order of 10**15 steps. Trial division stops being practical there.

Check a whole range: list all primes below N

If you need every prime up to some limit, calling is_prime on each number works for small limits. A comprehension keeps it short, as covered in Python list comprehension:

primes = [n for n in range(2, 100) if is_prime(n)]

For larger limits, the Sieve of Eratosthenes is much faster, because it crosses out multiples instead of dividing each number separately:

def primes_below(limit: int) -> list[int]:
    if limit <= 2:
        return []
    is_prime_flags = [True] * limit
    is_prime_flags[0] = is_prime_flags[1] = False
    for start in range(2, isqrt(limit - 1) + 1):
        if is_prime_flags[start]:
            for multiple in range(start * start, limit, start):
                is_prime_flags[multiple] = False
    return [n for n, flag in enumerate(is_prime_flags) if flag]

Example output of primes_below(30):

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Marking starts at start * start because smaller multiples of start were already crossed out by smaller primes. The sieve stores one flag per number, so memory use grows with the limit. Use it when you want many primes, and use is_prime when you want an answer for one number.

Check large numbers with sympy.isprime

For big integers, use SymPy, which is a third-party package (pip install sympy):

from sympy import isprime

isprime(2147483647)      # True
isprime(2**89 - 1)       # True
isprime(-2)              # False

The SymPy documentation describes isprime(n) as a layered test. It first looks for trivial factors, then for small numbers runs deterministic Miller-Rabin tests with bases known to have no counterexamples in their range, and for numbers above 2**64 it runs a strong BPSW test. The documentation states that for n below 2**64 the answer is definitive. Above that, the test is probabilistic: larger values have a small probability of being pseudoprimes, although the documentation notes there are no known counterexamples to the BPSW test. The function is meant for integer input, and floats are rejected because of limited precision.

So the practical split is simple. For a script that checks a few ordinary numbers, the standard-library loop is enough and has no dependency. For very large numbers, or when speed matters across many checks, isprime is the better tool. If you ever need a guarantee about a number above 2**64, treat a True as "almost certainly prime" and read the library's notes on certainty.

Common mistakes

  • Returning True for 1. A loop over range(2, n) never runs for n = 1 and falls through to return True. Add the explicit n < 2 guard.
  • Stopping the range one short. Without the + 1, squares of primes such as 9, 25 and 49 are reported as prime.
  • Passing a float. isqrt(17.0) raises a TypeError, because it requires an integer. Convert with int() only after confirming the value is whole.
  • Looping to n instead of the square root. The result is still correct but far slower: for 2147483647 that is about two billion iterations instead of 23,169.

If the results look wrong

Test the function against numbers whose status you can verify by hand: 0, 1, 2, 3, 4, 9, 25, 49, 91 and 97. Expect True only for 2, 3 and 97. If 9, 25 or 49 come back as prime, the range upper bound is off by one. If 1 comes back as prime, the guard is missing. If even numbers above 2 come back as prime, the early even check returns the wrong value.

Frequently asked questions

Is 1 a prime number?
No. A prime is a whole number greater than 1 whose only positive divisors are 1 and itself. The number 1 has only one divisor, so it is not prime, and a correct is_prime function must return False for 1, 0 and every negative number.
Why do you only check divisors up to the square root?
If n = a * b and both a and b were larger than the square root of n, their product would be larger than n. So every composite number has at least one divisor that is less than or equal to its square root, and if none is found up to that point, the number is prime.
What is the fastest way to check if a number is prime in Python?
For ordinary integers, sympy.isprime(n) is the simplest choice, because it combines trial division with Miller-Rabin tests and is definitive for n below 2**64. For one small number, a short trial-division loop with math.isqrt is fast enough and needs no install.
Can I use math.sqrt instead of math.isqrt?
You can, but math.sqrt returns a float, which has limited precision for very large integers and can round the wrong way. math.isqrt takes an integer and returns the exact floor of the square root, so it is the safer choice for a divisor limit.

Sources