forked from hanshulll/CodeCollection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounting Primes .cpp
78 lines (67 loc) · 1.32 KB
/
Counting Primes .cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<bits/stdc++.h>
using namespace std;
#define mx 10000009
typedef long long ll;
vector < int > primes;
void sieveOfEratosthenes()
{
bool flag[mx+1];
for(int i=0 ; i<=mx ; i++)
flag[i]=true;
primes.push_back(2);
flag[0]=flag[1]=false;
for(int i=4 ; i<=mx ; i+=2)
{
flag[i]=false;
}
for(int i=3 ; i<=mx ; i+=2)
{
if(flag[i]==true) /// i is prime
{
primes.push_back(i);
for(int j=i+i ; j<=mx ; j=j+i)
{
flag[j]=false; ///j is not prime
}
}
}
}
void segmentedSieve(ll L, ll R)
{
ll cnet=0;
bool isPrime[R-L+1];
for(int i=0 ; i<=R-L+1 ; i++)
isPrime[i]=true;
if(L==1)
isPrime[0]=false;
for(int i=0 ; primes[i]*primes[i]<=R ; i++)
{
ll curPrime=primes[i];
ll base=curPrime*curPrime;
if(base<L)
{
base=((L+curPrime-1)/curPrime)*curPrime;
}
for(ll j=base ; j<=R ; j+=curPrime)
isPrime[j-L]=false;
}
for(int i=0 ; i<=R-L ; i++)
{
if(isPrime[i]==true)
cnet++;
}
cout<<cnet<<"\n";
}
int main()
{
sieveOfEratosthenes();
ll t;
cin>>t;
while(t--)
{
ll a,b;
cin>>a>>b;
segmentedSieve(a,b);
}
return 0;
}