-
Notifications
You must be signed in to change notification settings - Fork 0
/
segmented sieve.cpp
65 lines (53 loc) · 1.26 KB
/
segmented sieve.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
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define LL long long
#define SET(x,n) (x[n>>6]|=(1<<((n>>1)&31)))
#define GET(x,n) (x[n>>6]&(1<<((n>>1)&31)))
vector < LL > prime;
void sieve(LL n){
LL sz = (n>>6)+1;
LL status[sz];
memset(status,0,sizeof status);
LL sqrtN = (LL)sqrt((double)n);
for(LL i=3;i<=sqrtN;i+=2){
if(!GET(status,i)){
prime.pb(i);
for(LL j=i*i;j<=n;j+=(i+i)){
SET(status,j);
}
}
}
}
void segmented_sieve(LL a, LL b){
LL sz = ((b-a+1)>>6)+1;
if(a<3){cout<<"2 "; a=3;}
if(a%2==0) a++;
LL status[sz];
memset(status,0,sizeof status);
LL sqrtN = (LL)((double) sqrt(b));
for(LL i=0;i<prime.size();i++){
LL p=prime[i];
LL j = p*p;
if(j<a)
j=p*((p+a-1)/p);
if(j%2==0) j+=prime[i];
for(;j<=b;j+=(p+p)){
if(j!=primes[i])
SET(status,(j-a));
}
}
for(LL i=a;i<=b;i+=2){
if(!GET(status,(i-a))){
cout<<i<<" ";
}
}
}
int main(){
LL a,b;
scanf("%lld%lld",&a,&b);
sieve(b);
segmented_sieve(a,b);
printf("\n");
return 0;
}