> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/number-theory/sieve-linear.md).

# 线性筛法（欧拉筛）

### 线性筛（欧拉筛）

每个合数只被它的**最小质因子**筛掉一次，因此复杂度是严格的 **O(n)**。

```cpp
const int N = 1000000;
int primes[N], cnt = 0;
bool notPrime[N + 1];

void linearSieve(int n) {
    for (int i = 2; i <= n; i++) {
        if (!notPrime[i]) primes[cnt++] = i;      // i 是素数
        for (int j = 0; j < cnt && i * primes[j] <= n; j++) {
            notPrime[i * primes[j]] = true;
            if (i % primes[j] == 0) break;        // 关键：保证只被最小质因子筛一次
        }
    }
}
```

### 为什么是 O(n)

每个合数只会被“最小质因子 × 剩余”标记一次，`if (i % primes[j] == 0) break;` 是核心。

### 与埃氏筛对比

|      | 埃氏筛            | 线性筛          |
| ---- | -------------- | ------------ |
| 复杂度  | O(n log log n) | O(n)         |
| 重复标记 | 有              | 无            |
| 用途   | 求素数表           | 求素数表 + 最小质因子 |

线性筛还能顺便求出每个数的**最小质因子**，用于质因数分解。

### 应用

* 预处理素数表（配合二分、数论题）
* 求约数个数、欧拉函数等积性函数


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/number-theory/sieve-linear.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
