Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7de2dc4

Browse files
Improved Sieve in O(n) time
1 parent a63d058 commit 7de2dc4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎improvedSieve.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /