Block sieving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
#define INF 1<<30 | |
#define maxn 100000005 | |
#define FASTIO ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); | |
typedef long long ll; | |
///Here we have an implementation that counts the number of primes | |
///smaller than or equal to n using block sieving. | |
int count_primes(int n) | |
{ | |
const int s = 10000; | |
vector<int> primes; | |
int nsqrt = sqrt(n); | |
vector<char> is_prime(nsqrt+1, true); | |
//for(auto x: is_prime) cerr << x<<endl; | |
for(int i = 2; i <= nsqrt; i++){ | |
if(is_prime[i]){ | |
primes.push_back(i); | |
for(int j = i * i; j <= nsqrt; j += i) | |
is_prime[j] = false; | |
} | |
} | |
int res = 0; | |
vector<char> block(s); | |
for(int k = 0; k*s <= n; k++){ | |
fill(block.begin(), block.end(), true); | |
int start = k * s; | |
for(int p: primes){ | |
int start_idx = (start + p - 1) / p; | |
int j = max(start_idx, p) * p - start; | |
for(; j < s; j += p) | |
block[j] = false; | |
} | |
if(k == 0) | |
block[0] = block[1] = false; | |
for(int i = 0; i < s && start + i <= n; i++){ | |
if(block[i]) | |
res++; | |
} | |
} | |
return res; | |
} | |
int main() | |
{ | |
FASTIO | |
///* | |
//double start_time = clock(); | |
#ifndef ONLINE_JUDGE | |
freopen("in.txt", "r", stdin); | |
freopen("out.txt", "w", stdout); | |
freopen("error.txt", "w", stderr); | |
#endif //*/ | |
int n; | |
cin >> n; | |
cout << count_primes(n) << "\n"; | |
//double end_time = clock(); | |
//printf( "Time = %lf ms\n", ( (end_time - start_time) / CLOCKS_PER_SEC)*1000); | |
return 0; | |
} |
No comments:
Post a Comment