Prime Sieve Of Eratosthenes Segmented (Python)

Generate all primes up to n using a segmented sieve of Eratosthenes for memory efficiency on large ranges.

PythonData Integrity

Code

pythonsnippet
24 lines
def segmented_sieve(n):
    if n < 2:
        return []
    limit = int(n ** 0.5) + 1
    base_primes = []
    is_comp = [False] * limit
    for i in range(2, limit):
        if not is_comp[i]:
            base_primes.append(i)
            for j in range(i * i, limit, i):
                is_comp[j] = True
    primes = list(base_primes)
    seg_size = 1 << 15
    for low in range(limit, n + 1, seg_size):
        high = min(low + seg_size - 1, n)
        seg = [False] * (high - low + 1)
        for p in base_primes:
            start = ((low + p - 1) // p) * p
            for j in range(start, high + 1, p):
                seg[j - low] = True
        for i in range(len(seg)):
            if not seg[i] and low + i >= 2:
                primes.append(low + i)
    return primes

How it works

Prime Sieve Of Eratosthenes Segmented (Python) keeps everything in the function segmented_sieve.

Iteration happens inside for i in range(2, limit) — everything outside it runs once.

It builds and returns a fresh value rather than reusing its inputs.

Using it

The main signature reads def segmented_sieve(n)

The surface worth importing is segmented_sieve; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Does `segmented_sieve` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `segmented_sieve` at load time.