> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/math/count-primes.md).

# Count Primes

> **Description:**
>
> Count the number of prime numbers less than a non-negative number,**n**.

## Thoughts

统计n以前的质数数字。Sieve of Eratosthenes。用一个长度为n的数组对应0\~n - 1，把其中不是prime的标出来。第一个prime是2，把能2的倍数全部在数组中标出来，即2\*2， 2\*3。。。直到2\*j >= n.然后i++ 移到下一个没被标记的prime, 即3，同理。直到i移到sqrt(n)为&#x6B62;**,** 因为大于sqrt(n)的j乘以i会超出n。

## Code

```cpp
/*
 * @lc app=leetcode id=204 lang=cpp
 *
 * [204] Count Primes
 */

// @lc code=start
class Solution {
public:
    int countPrimes(int n) {
         vector<bool> prims(n, true);
         for (int i = 2; i < sqrt(n); ++i) {
             if (!prims[i]) continue;
             for (int j = 2; i * j < n; ++j) {
                 prims[i * j] = false;
             }
         }
         int res = 0;
         for (int i = 2; i < n; ++i) {
             if (prims[i]) {
                 ++res;
             }
         }
         return res;
    }
};
// @lc code=end


```

## Analysis

Errors:

1. 用的是把prime存下来，判断i是否能和每个prime相%==0. TLE。除非加入判断是否超过square的语句:

```
for(int j=0;j<primes.size();j++){
if(primes.get(j)*primes.get(j)>i) break;
```

时间复杂度计算过于复杂，空间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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/math/count-primes.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
