Find the smallest prime palindrome greater than or equal to `N`.
Recall that a number is prime if it's only divisors are 1 and itself, and it is greater than 1.
For example, 2,3,5,7,11 and 13 are primes.
Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.
For example, 12321 is a palindrome.
Example 1:
Input: 6
Output: 7
Example 2:
Input: 8
Output: 11
Example 3:
Input: 13
Output: 101
Note:
1 <= N <= 10^8
- The answer is guaranteed to exist and be less than
2 * 10^8
.
這道題給了我們一個整數N,讓找一個大於等於N的回文質數,既要求是質數,又要求是回文數。其實這道題可以當作兩道題揉到了一起,判斷質數和回文數分別可以當作單獨的題。沒想太多,博主上來就准備暴力搜索,先寫兩個子函數,分別用來判斷質數和回文數,然后就直接從N開始搜索了,對每個數字都分別調用判斷質數和回文數的子函數,若都滿足,則返回該數即可。理想是豐滿的,現實是骨感的,OJ 教你做人系列之 TLE 超時!想着優化一下吧,直接跳過所有的偶數吧(2除外),還是跪。看來小優化是行不通,得大改。
問題出現在哪里了呢?肯定是判斷質數和回文數的子函數太占時間了,怎么優化呢?對於質數來說,非常的不規則,沒有太好的辦法來直接組成質數,而是需要通過驗證來看其是否為質數。而回文數就不一樣的,非常的有特點,我們可以直接按規律來組成回文數,而不是對每個數字都進行驗證,這樣的話就相當於去掉了驗證回文數的步驟,是一個相當大的提升。怎么拼接呢?由於給了N的取值范圍,我們可以遍歷前一半的所有數字,然后翻轉一下,組成后一半,兩個拼起來就是回文數了。但問題又來了,回文數的長度是分奇偶的,長度為奇數的回文數,最中間的數字是沒有對應的,腫么辦?其實這道題挺考數學知識的,用到了一個比較偏門的定理,就是所有長度為偶數的回文數字一定是 11 的倍數。博主表示從沒聽過這個定理,證明過程請參見 lee215 大神的帖子。通過這個定理,可以知道除了11之外,所有長度為偶數的回文數都不是質數,那么當N為 [8, 11] 中的數字時,才會返回11,這個就當 corner cases 提前判斷了,對於其他所有的都是符合規律的。那就可以只組奇數的回文數了,由於N的范圍是 [1, 1e8],所以前一半范圍是 [1, 1e5),因為還包含了最中間的那個數字,所以在翻轉之后,記得要把第一位數字去掉,因為最中間的數字只能保留一個,然后把兩個數字拼接起來。此時再判斷這個拼接后的數字是否大於等N,並且是否是質數,都滿足的話返回這個數字即可,參見代碼如下:
class Solution {
public:
int primePalindrome(int N) {
if (N >= 8 && N <= 11) return 11;
for (int i = 1; i < 1e5; ++i) {
string s = to_string(i), t(s.rbegin(), s.rend());
int x = stoi(s + t.substr(1));
if (x >= N && isPrime(x)) return x;
}
return -1;
}
bool isPrime(int num) {
if (num < 2 || num % 2 == 0) return num == 2;
int limit = sqrt(num);
for (int i = 3; i <= limit; ++i) {
if (num % i == 0) return false;
}
return true;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/866
類似題目:
參考資料:
https://leetcode.com/problems/prime-palindrome/
https://leetcode.com/problems/prime-palindrome/discuss/146798/Search-Palindrome-with-Odd-Digits
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)