-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprojectEuler037.cpp
More file actions
126 lines (96 loc) · 2.26 KB
/
Copy pathprojectEuler037.cpp
File metadata and controls
126 lines (96 loc) · 2.26 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/* Problem 37
Truncatable Primes
The number 3797 has an interesting property. Being prime itself, it is
possible to continuously remove digits from left to right, and remain
prime at each stage:
3797, 797, 97, and 7.
Similarly we can work from right to left:
3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from
left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
*/
#include <cmath>
#include <iostream>
#include <string>
using namespace std;
bool isPrime (int x) {
if (x == 1) {
return false;
}
if (x > 2 && x % 2 == 0) {
return false; // Other than 2, even numbers are not prime.
}
for (int divisor = 2; divisor <= floor (sqrt (double (x))); divisor++) {
if (x % divisor == 0) {
return false;
}
}
return true;
}
int removeRight (int x) {
string s = to_string (x);
s.erase (s.end () - 1);
int result = 0;
for (int i = 0; i < s.length (); i++) {
result += int (s [i] - 48) * pow (10, s.length () - 1 - i);
}
return result;
}
int removeLeft (int x) {
string s = to_string (x);
s.erase (s.begin ());
int result = 0;
for (int i = 0; i < s.length (); i++) {
result += int (s [i] - 48) * pow (10, s.length () - 1 - i);
}
return result;
}
int main () {
int sumTPrimes = 0;
int counter = 0;
for (int i = 10; i < 1000000; i++) {
bool leftPrimes = true;
bool rightPrimes = true;
if (isPrime (i)) {
int n = i;
string nStr = to_string (n);
// Left to right
while (n != 0) {
if (!isPrime (removeLeft (n))) {
leftPrimes = false;
break;
} else {
n = removeLeft (n);
nStr = to_string (n);
}
}
if (leftPrimes) {
n = i;
nStr = to_string (n);
// Right to left
while (n != 0) {
if (!isPrime (removeRight (n))) {
rightPrimes = false;
break;
} else {
n = removeRight (n);
nStr = to_string (n);
}
}
}
} else {
leftPrimes = false;
rightPrimes = false;
}
if (leftPrimes && rightPrimes) {
sumTPrimes += i;
cout << i << endl;
counter++;
}
if (counter == 11) {
break;
}
}
cout << sumTPrimes << endl;
}