Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

Check a Number or Generate a Range of Primes in Python

Use square-root-bounded trial division to test one integer, or SymPy’s sieve-based primerange to generate primes across a bounded interval.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To test one integer, use trial division up to its integer square root. To generate primes across a range, use a sieve such as SymPy’s primerange. These are different tasks: a simple standard-library function is useful for learning and individual checks, while a sieve avoids testing each number independently.

What counts as a prime number?

A prime is an integer greater than 1 whose only positive divisors are 1 and itself. That means negative integers, 0, and 1 are not prime; 2 is prime. Handling these boundaries first prevents common errors in a primality function.

As an Amazon Associate I earn from qualifying purchases.

Check whether one integer is prime

For a candidate n, you do not need to test every possible divisor up to n - 1. If n has a factor larger than its square root, it must also have a corresponding factor smaller than the square root. Testing through the integer square root is therefore sufficient. Python’s math.isqrt returns that floor value using integer arithmetic. See the Python 3.14.7 documentation for math.isqrt.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

The first condition rejects -1, 0, and 1. The even-number check accepts 2 but rejects other even values. The loop then checks odd divisors beginning at 3 and ending at the square-root bound, inclusive. For example, 13 has no divisor in that range and is prime; 21 is rejected because 3 divides it. If the loop finds no divisor, the function returns True implicitly.

Why skip even divisors?

After checking whether the candidate is even, every remaining possible divisor is odd, so the loop advances by 2. This is a straightforward reduction in checks, not a measured performance claim.

Generate every prime in a bounded range

If the goal is a list of primes rather than a yes-or-no answer for one candidate, use a sieve-based generator. SymPy’s primerange(a, b) includes a and excludes b. For example:

from sympy import primerange

primes = list(primerange(1, 30))
print(primes)

This produces [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]. The upper endpoint is excluded, so changing the call to primerange(1, 29) would omit 29. SymPy documents primerange and its dynamically growing sieve in its Number Theory documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the approach that matches the task

Approach Best fit Trade-off
Trial division with math.isqrt Learning the method or checking one moderate-sized integer without an added dependency Simple to understand, but not as suited to very large inputs as specialized primality routines.
SymPy primerange or sieve Generating primes in a bounded interval SymPy says sieve generation is generally faster than independent trial division, but uses more memory because values are stored.
SymPy isprime Convenient library-based checks of individual integers Requires SymPy; for inputs greater than 264, its documented strong BPSW method is a probable-prime test, not a proof.

There is no universal numeric cutoff in the cited documentation for when one method becomes preferable. The practical choice depends on whether you are checking a single value or generating a range, whether adding SymPy is acceptable, and how much memory is available.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use SymPy for a library-based primality check

When SymPy is already part of a project, its isprime function is a convenient alternative to writing trial division yourself:

from sympy import isprime

print(isprime(13))  # True
print(isprime(21))  # False

SymPy documents deterministic Miller–Rabin tests for smaller inputs and a strong BPSW test for values greater than 264. It describes the latter as a probable-prime test and reports no known counterexamples. Do not treat a result for every arbitrarily large input as a mathematical proof. The algorithm details are in the SymPy 1.14.0 Number Theory documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.