USACO SuperPrime Rib

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
67
68
69
70
71
72
73
74
75
76
/*
ID: wcr19961
PROG: sprime
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 10010;
const int tmp[] = {1, 3, 7, 9};
int p[1250], pnum;
bool np[maxn];
vector<int> bit[10];

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

bool isprime(int n) {
if (n < maxn) {
return !np[n];
}
for (int i = 0; i < pnum; ++i) {
if (n % p[i] == 0) {
return false;
}
}
return true;
}

int main() {
freopen("sprime.in", "r", stdin);
freopen("sprime.out", "w", stdout);
Euler_Prime();
bit[1].push_back(2);
bit[1].push_back(3);
bit[1].push_back(5);
bit[1].push_back(7);
int n;
scanf("%d", &n);
for (int i = 2; i <= n; ++i) {
for (int j = 0; j < bit[i - 1].size(); ++j) {
int x = bit[i - 1][j] * 10;
for (int k = 0; k < 4; ++k) {
if (isprime(x + tmp[k])) {
bit[i].push_back(x + tmp[k]);
}
}
}
}
sort(bit[n].begin(), bit[n].end());
for (int i = 0; i < bit[n].size(); ++i) {
printf("%d\n", bit[n][i]);
}
return 0;
}