-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimeSieve.cpp
More file actions
100 lines (98 loc) · 2.12 KB
/
PrimeSieve.cpp
File metadata and controls
100 lines (98 loc) · 2.12 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
using namespace std;
void bruteForcePN(int n)
{
if(n==1)
{
cout << "No, it's not a Prime" << endl;
return;
}
for(int i=2; i<=n-1; i++)
{
if(n%i==0)
{
cout << "No, it's not a Prime" << endl;
return;
}
}
cout << "Yes, it's a Prime" << endl;
return;
}
void bruteForcePNby2(int n)
{
if(n==1)
{
cout << "No, it's not a Prime" << endl;
return;
}
for(int i=2; i<=n/2; i++)
{
if(n%i==0)
{
cout << "No, it's not a Prime" << endl;
return;
}
}
cout << "Yes, it's a Prime" << endl;
return;
}
void rootNMethod(int n)
{
if(n==1)
{
cout << "No, it's not a Prime" << endl;
return;
}
for(int i=2; i*i<=n; i++) //for 1, 2, 3, 4, 6, 9, 12, 18, 36; check upto 6 only if any number divides 36 then it's not a prime
{
if(n%i==0)
{
cout << "No, it's not a Prime" << endl;
return;
}
}
cout << "Yes, it's a Prime" << endl;
return;
}
void Primesieve(long long int *sieve)
{
//Time:- O(nloglog) ~ O(n) so compute first
//mark all odds as prime
for(long long int i=3; i<= 1000000; i+=2)
{
sieve[i] = 1;
}
//now apply sieve logic
for(long long int i=3; i<= 1000000; i+=2)
{
//if marked now mark its multiple
if(sieve[i]==1)
{
//as for 5 next multiple will 25 because less than are already marked by number less then 5
for(long long int j= i*i; j<= 1000000; j=j+i)
{
sieve[j] = 0;
}
}
}
//special case
sieve[2] = 1;
sieve[1] = sieve[0] = 0;
}
int main() {
int n;
cin >> n;
bruteForcePN(n); //runs by O(n)
bruteForcePNby2(n); //runs by O(n/2)
rootNMethod(n); //runs by O(n^1/2)
long long int *sieve = new long long int[1000005]{0}; //runs by O(nloglogn) ~ O(n)
Primesieve(sieve);
for(int i=1; i<=100; i++)
{
if(sieve[i]==1)
{
cout << i << " ";
}
}
return 0;
}