USACO Prime Palindromes

Code

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
/*
ID: wcr19961
PROG: pprime
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <queue>
using namespace std;

typedef long long LL;
const int maxn = 10000010;
const int maxm = 664579;

int p[maxm], pnum;
unsigned int np[(maxn >> 5) + 1];

void Euler_Prime() {
for (LL i = 2; i < maxn; ++i) {
if (!(np[i >> 5] & (1 << (i % 32)))) {
p[pnum++] = i;
}
for (int j = 0; j < pnum; ++j) {
if (i * p[j] >= maxn) {
break;
}
np[(i * p[j]) >> 5] |= 1 << (i * p[j] % 32) ;
if (i % p[j] == 0) {
break;
}
}
}
}

int main() {
freopen("pprime.in", "r", stdin);
freopen("pprime.out", "w", stdout);
Euler_Prime();
int a, b, len, tmp[10], x;
scanf("%d%d", &a, &b);
int l = int(lower_bound(p, p + maxm, a) - p), r = int(upper_bound(p, p + maxm, b) - p);
for (int i = l; i < r; ++i) {
x = p[i], len = 0;
while (x) {
tmp[len] = x % 10;
x /= 10;
++len;
}
if ((len & 1) || p[i] == 11) {
bool ok = true;
for (int j = len >> 1; j < len; ++j) {
if (tmp[j] != tmp[len - j - 1]) {
ok = false;
break;
}
}
if (ok) {
printf("%d\n", p[i]);
}
}
}
return 0;
}