-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsieve .cpp
More file actions
56 lines (47 loc) · 1.13 KB
/
sieve .cpp
File metadata and controls
56 lines (47 loc) · 1.13 KB
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
///By the name of almighty Allah
#include<bits/stdc++.h>
using namespace std;
///sieve starts here
vector<int>prime;
bool mark[1000002];
void sieve(int n)
{
int i,j,limit=sqrt(n*1.0)+2;
mark[1]=true;
///mark 1 if it is not prime
for(i=4;i<=n;i+=2)
mark[i]=true;
///2 is prime
prime.push_back(2);
///run loop for only odds
for(i=3;i<=n;i+=2)
{
if(!mark[i])
{
///i is prime
prime.push_back(i);
///if we don't do it following
///i*i may be overflow
if(i<=limit)
{
///loop through all odd multiple off i
///greater than i*i because 3*3
for(j=i*i;j<=n;j+=i)
{
///mark j not prime
mark[j]=true;
}
}
}
}
vector<int>::iterator it;
for(it=prime.begin();it!=prime.end();it++)
cout<<*it<<" ";
}
int main()
{
int n;
cin>>n;
sieve(n);
return 0;
}