{
  "id": "sieve-of-eratosthenes",
  "title": "Sieve of Eratosthenes",
  "lang": "en",
  "source_lang": "en",
  "summary": "The sieve of Eratosthenes generates all prime numbers up to a chosen limit by repeatedly marking multiples of primes as composite.",
  "category": "mathematics",
  "subcategory": "algebra",
  "type": "concept",
  "aliases": [
    "Eratosthenes' sieve",
    "Eratosthenes sieve"
  ],
  "generated_at": "2026-11-04",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/sieve-of-eratosthenes/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/sieve-of-eratosthenes/",
      "json": "https://aiwiki.page/zh/sieve-of-eratosthenes.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The sieve of Eratosthenes is an algorithm for finding all prime numbers up to a specified limit. It begins with the integers from 2 to that limit and repeatedly marks the multiples of each successive prime as composite. The unmarked numbers remaining at the end are exactly the primes. Traditionally attributed to Eratosthenes, a Greek scholar of the third century BCE, it is a foundational method in computational number theory and remains practical in optimized forms."
    },
    {
      "heading": "Principle",
      "text": "A prime is an integer greater than 1 whose only positive divisors are 1 and itself. A composite number is an integer greater than 1 that is not prime. The number 1 is neither prime nor composite and is excluded from the sieve.\n\nThe sieve uses two elementary facts:\n\n- Every multiple \\(kp\\) of a prime \\(p\\), with \\(k\\geq 2\\), is composite.\n- Every composite integer \\(m\\) has a prime divisor no greater than \\(\\sqrt m\\).\n\nThe second fact follows by writing \\(m=ab\\), where \\(1<a\\leq b\\). Then \\(a\\leq\\sqrt m\\), and \\(a\\) has a prime divisor no greater than itself. The existence of prime divisors is part of the elementary theory underlying the fundamental theorem of arithmetic.\n\nConsequently, to find all primes up to \\(n\\), it is sufficient to mark multiples of primes no greater than \\(\\sqrt n\\). Every composite number up to \\(n\\) will then have been marked."
    },
    {
      "heading": "Procedure",
      "text": "For an integer upper limit \\(n\\geq 2\\):\n\n- Create a table of candidate flags indexed from 0 through \\(n\\).\n- Mark 0 and 1 as not prime, leaving all other entries initially unmarked.\n- Starting with \\(p=2\\), inspect each integer \\(p\\) while \\(p^2\\leq n\\).\n- If \\(p\\) is unmarked, mark\n\n\\[p^2,\\ p^2+p,\\ p^2+2p,\\ldots\\]\n\nthrough the last such number not exceeding \\(n\\).\n- Read off all unmarked integers from 2 through \\(n\\).\n\nMarking begins at \\(p^2\\), rather than \\(2p\\), because every smaller multiple \\(kp\\), where \\(2\\leq k<p\\), has a prime divisor smaller than \\(p\\) and has already been marked.\n\nA direct implementation is:\n\nfunction sieve(n):\n    if n < 2:\n        return empty list\n\n    candidate = array indexed 0 through n, initialized to true\n    candidate[0] = false\n    candidate[1] = false\n\n    p = 2\n    while p * p <= n:\n        if candidate[p]:\n            multiple = p * p\n            while multiple <= n:\n                candidate[multiple] = false\n                multiple = multiple + p\n        p = p + 1\n\n    return all i from 2 through n for which candidate[i] is true\n\nIn fixed-width integer implementations, evaluating \\(p^2\\) may overflow. For positive \\(p\\), the loop condition can instead be expressed as \\(p\\leq\\lfloor n/p\\rfloor\\), with corresponding care when advancing the marking index.\n\nExample: primes up to 30\n\nInitially, all integers from 2 through 30 are candidates.\n\nPrime used | Numbers marked, beginning at its square\n2 | 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30\n3 | 9, 12, 15, 18, 21, 24, 27, 30\n5 | 25, 30\n\nThe entry for 4 is skipped because it has already been marked. Once 5 has been processed, no further sieving prime is necessary because \\(7^2>30\\).\n\nThe surviving numbers are\n\n\\[2,\\ 3,\\ 5,\\ 7,\\ 11,\\ 13,\\ 17,\\ 19,\\ 23,\\ 29.\\]\n\nRepeatedly marking an already marked number, such as 12 or 30, is harmless."
    },
    {
      "heading": "Correctness",
      "text": "The sieve’s correctness proof has two parts.\n\nNo prime is marked. Every marked integer has the form \\(p(p+k)\\), where \\(p\\geq 2\\) and \\(k\\geq 0\\). It therefore has a nontrivial divisor and cannot be prime.\n\nEvery composite is marked. Let \\(m\\leq n\\) be composite, and let \\(q\\) be its smallest prime divisor. Then \\(q\\leq\\sqrt m\\leq\\sqrt n\\), so the algorithm reaches \\(q\\). Since primes are never marked, its marking pass is performed. Moreover, \\(m/q\\geq q\\); otherwise \\(m\\) would have a prime divisor smaller than \\(q\\). Thus \\(m\\geq q^2\\), placing it among the multiples marked in that pass.\n\nThese statements establish that the surviving entries are exactly the primes up to \\(n\\)."
    },
    {
      "heading": "Time and space complexity",
      "text": "Under a standard model in which indexing and marking a table entry take constant time, the sieve uses\n\n\\[O(n\\log\\log n)\\]\n\ntime, expressed in Big O notation.\n\nFor each prime \\(p\\leq\\sqrt n\\), approximately \\(n/p\\) entries are visited. The marking work is therefore bounded by a constant multiple of\n\n\\[n\\sum_{\\substack{p\\leq\\sqrt n\\\\p\\text{ prime}}}\\frac{1}{p}.\\]\n\nThe sum of reciprocals of primes up to \\(x\\) grows as \\(\\log\\log x+O(1)\\), giving the stated bound. Initializing and scanning the table each require an additional \\(O(n)\\) operations.\n\nThe ordinary sieve uses \\(O(n)\\) flag storage. A packed representation requires \\(O(n)\\) bits, whereas implementations using a byte or a machine word for each flag have larger memory requirements. If all primes are also stored explicitly, the output list occupies additional space. By the prime number theorem, the number of primes up to \\(n\\) is asymptotic to \\(n/\\log n\\).\n\nThese bounds concern the numerical limit \\(n\\), not its input length. Writing \\(n\\) in binary takes only \\(O(\\log n)\\) bits, while the sieve processes a range containing approximately \\(n\\) integers."
    },
    {
      "heading": "Practical variants",
      "text": "Odd-only sieve\n\nAfter recording 2 separately, an implementation can represent only odd integers. For an odd prime \\(p\\), its odd multiples beginning at \\(p^2\\) are separated by \\(2p\\). This roughly halves candidate storage and avoids marking even numbers, without changing the asymptotic complexity.\n\nSegmented sieve\n\nA segmented sieve divides the target range into blocks instead of retaining one table for the whole range.\n\nFirst, it generates the base primes through \\(\\lfloor\\sqrt n\\rfloor\\). For a block \\([L,R]\\), each base prime \\(p\\) marks multiples starting at\n\n\\[\\max\\left(p^2,\\left\\lceil\\frac{L}{p}\\right\\rceil p\\right).\\]\n\nThe ceiling expression identifies the first multiple of \\(p\\) in the block, while the \\(p^2\\) condition prevents the prime itself from being marked. Any entries below 2 are excluded separately.\n\nOnly the current block and the base-prime data need to remain in memory. With a block containing \\(S\\) candidate positions, a straightforward implementation uses \\(O(S)\\) flags plus storage for the primes through \\(\\sqrt n\\). Segmentation also improves locality of memory access, making it important for large computations.\n\nBlock size affects performance: repeatedly inspecting every base prime for very small blocks can introduce substantial overhead. More advanced implementations maintain the next marking position for each prime or organize future marking work into buckets.\n\nWheel factorization\n\nA wheel omits numbers divisible by several small primes, rather than only by 2. For example, after handling 2, 3, and 5 separately, candidates can be restricted to the eight residue classes coprime to 30. This uses modular arithmetic to reduce candidate density.\n\nWheels reduce storage and marking work but complicate indexing and traversal. A wheel is a filtering mechanism, not a complete prime generator by itself: surviving candidates still require sieving.\n\nParallel processing\n\nDifferent segments can be processed independently once the base primes are known, making segmentation suitable for parallel computing. Practical performance depends on memory bandwidth, workload distribution, and the cost of collecting the results."
    },
    {
      "heading": "Relationship to other methods",
      "text": "The sieve differs from trial division. Trial division examines an individual candidate and tests whether smaller primes divide it. The sieve instead processes each small prime and eliminates many candidates at once. This shared work makes it particularly effective when a complete range of primes is required.\n\nA linear sieve, often called Euler’s sieve, arranges for each composite to be generated once through its smallest prime factor and achieves \\(O(n)\\) operations in a standard unit-cost model. It commonly stores more information than a bit-packed Eratosthenes sieve and is not necessarily faster in practice.\n\nOther prime-generating algorithms, such as the sieve of Atkin, use different mathematical criteria. Their theoretical operation counts do not alone determine practical speed; representation, memory access, and implementation complexity also matter."
    },
    {
      "heading": "Uses and limitations",
      "text": "The sieve is widely used to construct prime tables, support experiments in number theory, and provide small primes for other algorithms. Once its table has been built, whether an integer within the represented range is prime can be answered by a single table lookup.\n\nRelated sieving techniques can tabulate smallest prime factors, divisor counts, and other arithmetic functions, although these extensions may require additional storage and different update rules.\n\nThe method is less suitable when the task is to determine whether one extremely large integer is prime. Sieving up to that integer requires processing an enormous range; even sieving a narrow interval near it normally requires base primes up to approximately its square root. Dedicated primality tests address this different problem without enumerating all preceding primes."
    }
  ],
  "links": [
    "algorithm",
    "prime-number",
    "eratosthenes",
    "number-theory",
    "integer",
    "composite-number",
    "fundamental-theorem-of-arithmetic",
    "mathematical-proof",
    "big-o-notation",
    "prime-number-theorem",
    "modular-arithmetic",
    "parallel-computing",
    "primality-test"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}