Skip to content

Commit 7cc29b8

Browse files
committed
Segmented Sieve CPP
1 parent accd71f commit 7cc29b8

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
//Segemented Sieve: Generate prime numbers less than N
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
typedef long long ll;
5+
void simpleSieve(ll limit, vector<ll>& prime){
6+
bool isPrime[limit+1];
7+
memset(isPrime, true, sizeof(isPrime));
8+
for(int i=2;i*i<limit;++i){
9+
if(isPrime[i]){
10+
for(int j=i*i;j<limit;j+=i){
11+
isPrime[j] = false;
12+
}
13+
}
14+
}
15+
for(int i=2;i<limit;i++){
16+
if(isPrime[i]){
17+
cout<<i<<" ";
18+
prime.push_back(i);
19+
}
20+
}
21+
}
22+
void segmentedSieve(ll n){
23+
ll limit = sqrt(n)+1;
24+
vector<ll> prime;
25+
simpleSieve(limit,prime);
26+
ll low = limit;
27+
ll high = 2*limit;
28+
while(low<n){
29+
if(high>n){
30+
high = n;
31+
}
32+
bool mark[limit+1];
33+
memset(mark, true, sizeof(mark));
34+
for(int i=0;i<prime.size();++i){
35+
ll curPrime = prime[i];
36+
ll base = (low/curPrime)*curPrime;
37+
if(base<low){
38+
base = base + curPrime;
39+
}
40+
for(int j=base;j<high;j+=curPrime){
41+
mark[j-low] = false;
42+
}
43+
if(base==curPrime)
44+
mark[base-low] = true;
45+
}
46+
for(int i=low;i<high;i++){
47+
if(mark[i-low])
48+
cout<<i<<" ";
49+
}
50+
low = low + limit;
51+
high = high + limit;
52+
}
53+
}
54+
int main()
55+
{
56+
segmentedSieve(10000);
57+
}

0 commit comments

Comments
 (0)