Prime Sieve Of Eratosthenes Segmented (Python)
Generate all primes up to n using a segmented sieve of Eratosthenes for memory efficiency on large ranges.
Code
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 primesHow 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
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.