File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed
Math/sieve_of_eratosthenes Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ // print all primes smaller than
2
+ // n using segmented sieve
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+ void simpleSieve (int limit, vector<int > &prime)
6
+ {
7
+
8
+ bool mark[limit+1 ];
9
+ memset (mark, true , sizeof (mark));
10
+
11
+ for (int p=2 ; p*p<limit; p++)
12
+ {
13
+
14
+ if (mark[p] == true )
15
+ {
16
+
17
+ for (int i=p*2 ; i<limit; i+=p)
18
+ mark[i] = false ;
19
+ }
20
+ }
21
+
22
+ for (int p=2 ; p<limit; p++)
23
+ {
24
+ if (mark[p] == true )
25
+ {
26
+ prime.push_back (p);
27
+ cout << p << " " ;
28
+ }
29
+ }
30
+ }
31
+
32
+ void segmentedSieve (int n)
33
+ {
34
+ int limit = floor (sqrt (n))+1 ;
35
+ vector<int > prime;
36
+ simpleSieve (limit, prime);
37
+
38
+ int low = limit;
39
+ int high = 2 *limit;
40
+
41
+ while (low < n)
42
+ {
43
+
44
+ bool mark[limit+1 ];
45
+ memset (mark, true , sizeof (mark));
46
+
47
+ for (int i = 0 ; i < prime.size (); i++)
48
+ {
49
+
50
+ int loLim = floor (low/prime[i]) * prime[i];
51
+ if (loLim < low)
52
+ loLim += prime[i];
53
+
54
+ for (int j=loLim; j<high; j+=prime[i])
55
+ mark[j-low] = false ;
56
+ }
57
+
58
+ for (int i = low; i<high; i++)
59
+ if (mark[i - low] == true )
60
+ cout << i << " " ;
61
+
62
+ low = low + limit;
63
+ high = high + limit;
64
+ if (high >= n) high = n;
65
+ }
66
+ }
67
+
68
+ int main ()
69
+ {
70
+ int n = 100 ;
71
+ cout << " Primes smaller than " << n << " :n " ;
72
+ segmentedSieve (n);
73
+ cout<<" \n " ;
74
+ return 0 ;
75
+ }
You can’t perform that action at this time.
0 commit comments