forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
82 lines (65 loc) · 2.14 KB
/
main2.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
/// Source : https://leetcode.com/problems/prime-palindrome/solution/
/// Author : liuyubobobo
/// Time : 2018-07-07
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/// Recursively generate all prime palindrome number
/// Ignore all even-digit palindrome number
/// Because, interestingly, all even-digit palindrome number is not prime, except 11 :)
/// The proof is in the official solution of this problem:
/// https://leetcode.com/problems/prime-palindrome/solution/
///
/// Time Complexity: O(maxN)
/// Space Complexity: O(?)*
///
/// * It is not even known whether there are infinitely many prime palindromes,
/// Basically, it's an open mathematical problem
/// But we can roughly say the time and space complexity is O(n) :)
class Solution {
public:
int primePalindrome(int N) {
vector<int> nums = {2, 3, 5, 7, 11};
for(int d = 3; d <= 8 ; d += 2)
generatePalindromePrimes(d, nums);
nums.push_back(100030001);
sort(nums.begin(), nums.end());
return *lower_bound(nums.begin(), nums.end(), N);
}
private:
void generatePalindromePrimes(int d, vector<int>& nums){
string s(d, '-');
generatePalindromePrimes(0, s, nums);
}
void generatePalindromePrimes(int index, string& s, vector<int>& nums){
if(s[index] != '-'){
int num = atoi(s.c_str());
if(isPrime(num))
nums.push_back(num);
return;
}
int start = 0;
if(index == 0)
start = 1;
for(int d = start ; d <= 9 ; d ++){
s[index] = s[s.size() - 1 - index] = ('0' + d);
generatePalindromePrimes(index + 1, s, nums);
s[index] = s[s.size() - 1 - index] = '-';
}
}
bool isPrime(int x){
if(x % 2 == 0)
return false;
for(int i = 3 ; i * i <= x ; i ++)
if(x % i == 0)
return false;
return true;
}
};
int main() {
cout << Solution().primePalindrome(6) << endl;
cout << Solution().primePalindrome(8) << endl;
cout << Solution().primePalindrome(13) << endl;
return 0;
}