-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem037.cpp
88 lines (81 loc) · 1.79 KB
/
problem037.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <vector>
#include <math.h>
#include <sstream>
#include <algorithm>
#include <string>
using namespace std;
string toStr(int n)
{
stringstream ss;
ss << n;
return ss.str();
}
vector<bool> sieve(int n)
{
vector<bool> primes(n, true);
int squareN = sqrt(n);
for (int i = 2; i < squareN; i++)
{
if (primes[i])
{
for (int j = pow(i, 2); j < n; j += i)
{
primes[j] = false;
}
}
}
return primes;
}
vector<int> getRightNums(int i)
{
vector<int> nums;
string number = toStr(i);
for (int i = 0; i < number.size(); i++)
{
string partNum = number.substr(0, i + 1);
nums.push_back(atoi(partNum.c_str()));
}
return nums;
}
vector<int> getLeftNums(int i)
{
vector<int> nums;
string number = toStr(i);
for (int i = 0; i < number.size(); i++)
{
string partNum = number.substr(i, number.size() - 1);
nums.push_back(atoi(partNum.c_str()));
}
return nums;
}
int main()
{
vector<bool> primes = sieve(1000000);
primes[0] = false;
primes[1] = false;
int total = 0;
for (int i = 10; i < primes.size(); i++)
{
if (primes[i])
{
vector<int> leftSideNums = getLeftNums(i);
vector<int> rightSideNums = getRightNums(i);
bool truncPrime = true;
for (int j = 0; j < leftSideNums.size(); j++)
{
if (!primes[leftSideNums[j]] || !primes[rightSideNums[j]])
{
truncPrime = false;
}
}
if (truncPrime)
{
total += i;
cout << i << endl;
}
}
}
cout << total << endl;
return 0;
}