-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathseive_of_eratosthenes.cpp
65 lines (56 loc) · 1.1 KB
/
seive_of_eratosthenes.cpp
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
/*
Given a number N, calculate the prime numbers upto N using Sieve of Eratosthenes.
Input:
The first line of the input contains T denoting the number of testcases. T testcases follow. Each testcase contains one line of input containing N.
Output:
For all testcases, in a new line, print all the prime numbers upto or equal to N.
Constraints:
1 <= T<= 100
1 <= N <= 104
Example:
Input:
2
10
35
Output:
2 3 5 7
2 3 5 7 11 13 17 19 23 29 31
*/
#include <bits/stdc++.h>
using namespace std;
void seive(int n)
{
bool seive[n + 1];
fill(seive, seive + n + 1, true);
for (int p = 2; p * p <= n; p++)
{
if (seive[p] == true)
{
for (int i = p * p; i <= n; i += p)
{
seive[i] = false;
}
}
}
for (int p = 2; p <= n; p++)
{
if (seive[p] == true)
cout << p << " ";
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
seive(n);
cout << endl;
}
return 0;
}