-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathPRIME1.cpp
55 lines (44 loc) · 1.04 KB
/
PRIME1.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
/*
math > number theory > prime numbers > sieve of eratosthenes
difficulty: medium
date: 17/Mar/2020
problem: print all primes p in [m .. n], 0 <= m <= n <= 10^9, n-m <= 10^5
hint: sieve + prime checking
by: @brpapa
*/
#include <iostream>
#include <vector>
#include <bitset>
#include <cmath>
using namespace std;
vector<int> primes;
bitset<35001> is;
void sieve(int ub) {
is.set(); is[0] = is[1] = false;
for (int i = 2; i < ub; i++)
if (is[i]) {
for (int j = i*i; j < ub; j += i)
is[j] = false;
primes.push_back(i);
}
}
bool isPrime(int n) {
if (n <= primes.back()) return is[(int)n];
int sn = (int) sqrt(n);
for (int p : primes) {
if (p > sn) break;
if (n % p == 0) return false;
}
return true;
}
int main() {
sieve(35000); // maior que sqrt(10^9)
int T; cin >> T;
while (T--) {
int m, n; cin >> m >> n;
for (int i = m; i <= n; i++)
if (isPrime(i)) cout << i << endl;
if (T > 0) cout << endl;
}
return 0;
}