forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path37.cpp
More file actions
78 lines (65 loc) · 1.36 KB
/
37.cpp
File metadata and controls
78 lines (65 loc) · 1.36 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
/**
* Problem: Find the sum of all eleven primes that are both truncatable from left to right and right to left.
* Algorithm: DFS
* Author: daiwb
* Date: 2008/08/31
*/
#include <iostream>
#include <sstream>
#include <set>
#include <cmath>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
typedef long long LL;
int res;
int num[4] = {1, 3, 7, 9};
int string2int(string str) {
stringstream ss;
ss << str;
int res;
ss >> res;
return res;
}
bool isprime(int val) {
if (val == 2 || val == 3 || val == 5 || val == 7) return true;
if (val == 1) return false;
int mid = (int)sqrt(val + 0.5);
if ((val & 1) == 0) return false;
for (int i = 3; i <= mid; i += 2) {
if ((val % i) == 0) return false;
}
return true;
}
bool isok(string str) {
if (str.length() == 1) return false;
REP(len,str.length()) {
string s = str.substr(len);
if (!isprime(string2int(s))) return false;
s = str.substr(0, len + 1);
if (!isprime(string2int(s))) return false;
}
return true;
}
void dfs(string str) {
stringstream ss;
ss << str;
int val;
ss >> val;
if (!isprime(val)) return;
if (isok(str)) {
res += val;
}
REP(i,4) dfs(str + char(num[i] + '0'));
}
void run() {
res = 0;
dfs("2");
dfs("3");
dfs("5");
dfs("7");
cout << res << endl;
}
int main() {
run();
}