algorithm increases the number of prime-seeking
Time limit: 1.0s memory limit: 256.0MB problem Description
For a given interval [L, R], calculate the number of primes in the interval. Input Format
Two numbers L and R. output Format
Row, the number of primes in the interval. Sample Input
2 Sample Output
5 data size and conventions
2 <= L <= R <= 2147483647 r-l <= 1000000
Test instructions: Slightly
Analysis: Know the general prime sieve method should all know the principle, here is actually a simulation where the Sieve method, analysing as follows: 1. preprocess all primes in [0,2147483647] 2. Use [0,r-l] to represent [l,r], find the corresponding relationship 3. Sieve number by the thought of sieve method, For example the first prime 2,[l,l+2] there must be a multiple of 2, find the starting point, and then sweep it down again.
4. Consider whether 3 of the practice is reasonable, because the scope of the r-l is 1e6, time limit, consider optimization, we can think of in fact we can find the starting point in O (1) time, there are only a few cases: <1> when the prime number P >= L, we just need to place the starting point at P-l Place < ;2> Otherwise, consider whether L% p is 0, if 0, then 0 points, otherwise at p-l P <3> if the current starting point + L is a prime number, you should go back to p units
5. O (n) statistics can refer to the code
#include <bits/stdc++.h> using namespace std;
const int MAXN = 1e6 + 7;
int m = (int) sqrt (2147483647+0.5) + 10;
BOOL ISP[MAXN];
int P[MAXN/10];
int Len;
void Init () {isp[0] = isp[1] = true;
for (int i = 2; i < m; i++) {if (!isp[i]) p[++len] = i;
for (int j = 1; J <= Len && p[j]*i < M; j + +) {Isp[i*p[j]] = true;
if (i% p[j] = = 0) break;
}}} int main () {init ();
memset (isp,false,sizeof ISP);
int l,r;cin>>l>>r;
int Len = r-l + 1;
for (int i = 1; I <= len; i++) {int L;
if (P[i] >= l) L = p[i]-l;
else {if (l% p[i] = = 0) L = 0;
else L = p[i]-l%p[i];
if (l + L = = P[i]) L + = p[i];
for (int j = L; J <= Len; j + = P[i]) {isp[j] = true;
}} int cnt = 0;
for (int i = 0; i < Len; i++) {if (!isp[i]) cnt++;
} if (L = = 1) cnt--; cout<<cnt<<endl;
return 0;
}
If you have any errors or omissions, please talk to up,thx in private.