cpplib

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub morioprog/cpplib

:heavy_check_mark: エラトステネスの篩
(math/prime/eratosthenes.hpp)

概要

$n$以下の素数判定を高速に行う.

計算量

$O(n\log\log{n})$

使用例

Verified with

Code

/**
* @brief エラトステネスの篩
* @docs docs/math/prime/eratosthenes.md
*/

vector<bool> eratosthenes(const int n) {
    vector<bool> r(n + 1, true);
    for (int i = 2; i * i <= n; ++i) {
        if (r[i]) {
            for (int j = i * 2; j <= n; j += i) r[j] = false;
        }
    }
    if (r.size() > 2) {
        r[0] = r[1] = false;
    } else if (r.size() > 1) {
        r[0] = false;
    }
    return r;
}
#line 1 "math/prime/eratosthenes.hpp"
/**
* @brief エラトステネスの篩
* @docs docs/math/prime/eratosthenes.md
*/

vector<bool> eratosthenes(const int n) {
    vector<bool> r(n + 1, true);
    for (int i = 2; i * i <= n; ++i) {
        if (r[i]) {
            for (int j = i * 2; j <= n; j += i) r[j] = false;
        }
    }
    if (r.size() > 2) {
        r[0] = r[1] = false;
    } else if (r.size() > 1) {
        r[0] = false;
    }
    return r;
}
Back to top page