Prime Sieve Of Eratosthenes Segmented (Go)
Generate all primes up to n in Go using a segmented sieve of Eratosthenes for memory efficiency.
Code
package main
import "math"
func segmentedSieve(n int) []int {
if n < 2 { return nil }
limit := int(math.Sqrt(float64(n))) + 1
var basePrimes []int
isComp := make([]bool, limit)
for i := 2; i < limit; i++ { if !isComp[i] { basePrimes = append(basePrimes, i); for j := i * i; j < limit; j += i { isComp[j] = true } } }
primes := append([]int{}, basePrimes...)
segSize := 1 << 15
for low := limit; low <= n; low += segSize {
high := low + segSize - 1; if high > n { high = n }
seg := make([]bool, high-low+1)
for _, p := range basePrimes { start := ((low + p - 1) / p) * p; for j := start; j <= high; j += p { seg[j-low] = true } }
for i := 0; i < len(seg); i++ { if !seg[i] && low+i >= 2 { primes = append(primes, low+i) } }
}
return primes
}The shape of the execution
Count the function segmentedSieve as the entire surface area of Prime Sieve Of Eratosthenes Segmented (Go).
Iteration happens inside for i := 2; i < limit; i++ { if !isComp[i] { basePrimes = append(basePrimes, i); for j := i * i; … — everything outside it runs once.
Applying it
Entry signature: func segmentedSieve(n int) []int
Statements that matter
for _, p := range basePrimes { start := ((low + p - 1) / p) * p; for j := start; j <= high; j += p { seg[j-low] = true } }
for i := 0; i < len(seg); i++ { if !seg[i] && low+i >= 2 { primes = append(primes, low+i) } }
primes := append([]int{}, basePrimes...)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.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.
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `segmentedSieve` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.