质数判断:修订间差异
跳转到导航
跳转到搜索
创建页面,内容为“==判断单个质数== <math>O(\sqrt{x})</math> <syntaxhighlight lang="cpp" line> bool is_prime(long long x) { if (x < 2) return false; for (long long i = 2; i * i <= x; i++) if (x % i == 0) return false; return true; } </syntaxhighlight> ==筛法== ===埃氏筛=== <math>O(n\log \log n)</math> <syntaxhighlight lang="cpp" line> const int MAXN = 10'000'000; bool p[MAXN + 1]; //筛出 1~n 中的每个数是否为质数…” |
|||
| 第60行: | 第60行: | ||
{ | { | ||
// i*pri[j] | // i*pri[j] | ||
if (i * pri[j] > n) | if (1LL * i * pri[j] > n) | ||
break; | break; | ||
p[i * pri[j]] = false; | p[i * pri[j]] = false; | ||
2026年2月26日 (四) 03:04的最新版本
判断单个质数
[math]\displaystyle{ O(\sqrt{x}) }[/math]
bool is_prime(long long x)
{
if (x < 2)
return false;
for (long long i = 2; i * i <= x; i++)
if (x % i == 0)
return false;
return true;
}
筛法
埃氏筛
[math]\displaystyle{ O(n\log \log n) }[/math]
const int MAXN = 10'000'000;
bool p[MAXN + 1];
//筛出 1~n 中的每个数是否为质数
void get_primes(int n)
{
//初始化
p[0] = p[1] = false;
for (int i = 2; i <= n; i++)
p[i] = true;
//筛
for (int i = 2; i <= n; i++)
if (p[i])
for (int j = i + i; j <= n; j += i)
p[j] = false;
}
线性筛/欧拉筛
[math]\displaystyle{ O(n) }[/math]
const int MAXN = 10'000'000;
bool p[MAXN + 1];
vector<int> pri;
// 筛出 1~n 中的每个数是否为质数
void get_primes(int n)
{
for (int i = 1; i <= n; i++)
p[i] = true;
p[0] = p[1] = false;
for (int i = 2; i <= n; i++)
{
if (p[i])
pri.push_back(i);
for (int j = 0; j < pri.size(); j++)
{
// i*pri[j]
if (1LL * i * pri[j] > n)
break;
p[i * pri[j]] = false;
if (i % pri[j] == 0)
break;
}
}
}