File tree 1 file changed +35
-0
lines changed
1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Given N, find all primes less than N in O(N) time
2
+ #include < bits/stdc++.h>
3
+ #define ll long long
4
+ #define MAX_SIZE 100001
5
+ using namespace std ;
6
+
7
+ vector<ll> prime; // to store the primes
8
+ vector<bool > isPrime (MAX_SIZE, true );
9
+ vector<ll> SPF (MAX_SIZE); // SPF[i] stores smallest prime factor of i
10
+
11
+ void improvedSieve (ll n) {
12
+ ll i,j;
13
+ isPrime[0 ] = isPrime[1 ] = false ;
14
+ for (i=2 ;i<n;i++) {
15
+ if (isPrime[i]) {
16
+ prime.push_back (i);
17
+ SPF[i] = i; // since smallest prime factor of a prime is the prime itself
18
+ }
19
+ for (j=0 ;j<prime.size () && i*prime[j]<n && prime[j]<=SPF[i]; j++) {
20
+ isPrime[i*prime[j]] = false ;
21
+ SPF[i*prime[j]] = prime[j];
22
+ }
23
+ }
24
+ }
25
+
26
+ int main () {
27
+ ll n;
28
+ cin>>n;
29
+ improvedSieve (n);
30
+ for (ll i=0 ;i<prime.size ();i++ ) {
31
+ cout<<prime[i]<<" " ;
32
+ }
33
+ cout<<endl;
34
+ return 0 ;
35
+ }
You can’t perform that action at this time.
0 commit comments