asd890123 @ 2024-06-26 09:29:56
埃筛:
#include <iostream>
#include <cstring>
#include <bitset>
const int N = 1e8 + 5;
int prime[N];
std::bitset <N> isPrime;
int main(){
std::cin.tie(0)->sync_with_stdio(0);
int n,q,cnt = 0;
std::cin >> n >> q;
isPrime.set();
isPrime[0] = isPrime[1] = false;
for (int i = 2;i * i <= n;i++)
if (isPrime[i])
for (int j = i * i;j <= n;j += i)
isPrime[j] = false;
for (int i = 2;i <= n;i++)
if (isPrime[i])
prime[++cnt] = i;
while (q--){
int k;
std::cin >> k;
std::cout << prime[k] << '\n';
}
return 0;
}
记录 欧筛:
#include <iostream>
#include <cstring>
#include <bitset>
const int N = 1e8 + 5;
int prime[N];
std::bitset <N> isPrime;
int main(){
std::cin.tie(0)->sync_with_stdio(0);
int n,q,cnt = 0;
std::cin >> n >> q;
isPrime.set();
isPrime[0] = isPrime[1] = false;
for (int i = 2;i <= n;i++){
if (isPrime[i]) prime[++cnt] = i;
for (int j = 1;j <= cnt && i * prime[j] <= n;j++){
isPrime[i * prime[j]] = false;
if (i % prime[j] == 0) break;
}
}
while (q--){
int k;
std::cin >> k;
std::cout << prime[k] << '\n';
}
return 0;
}
记录
by WydnksqhbD @ 2024-06-26 09:43:55
@asd890123
by WydnksqhbD @ 2024-06-26 09:45:16
@asd890123 去掉 bitset
后
by asd890123 @ 2024-06-26 09:53:29
但是为什么欧筛用bool和bitset几乎不变,埃筛一开bitset就起飞@WydnksqhdD
by asd890123 @ 2024-06-26 09:54:05
@WydnksqhbD
by WydnksqhbD @ 2024-06-26 09:56:49
@asd890123 常数问题吧,取模直接起飞了。
by Leo2011 @ 2024-07-07 15:53:15
实测都开 O2,bitset + 埃氏筛 远超 bool 数组 + 欧拉筛,时间和空间都是埃氏筛占优。
所以,该让埃氏筛水过吗?
by Leo2011 @ 2024-07-07 15:58:59
@Leo2011 不对,埃氏筛有快读加持,但影响应该不大
by dbycs11 @ 2024-07-14 11:49:27
@Leo2011 影响不大,把线性筛加上快读、用bitset还是比普通筛+bitset慢100多ms