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
.
发现有个规律ABCCBA,ABCDDCBA这种偶数形式的一定不是质数(11除外),一定是11的倍数,所以只要找奇数位长度的数了
然后以为穷举+判断是不是prime即可,搜索的GeeksForGeeks的答案都是求出所有质数,然后循环,好无语,
自己真应该先试一下自己的穷举+判断是不是prime的想法的,乱七八糟的搜类似的题还真是浪费很多时间
class Solution:
def primePalindrome(self, n):
"""
:type N: int
:rtype: int
"""
def isPrime(t):
if t==1: return False
i = 2
while i*i<=t:
if t%i==0: return False
i+=1
return True
if n<110:
for i in range(n, 1000000):
if str(i)==str(i)[::-1] and isPrime(i): return i
s=str(n)
if len(s)%2==0:
p=len(s)//2
t=int('1'+'0'*(p))
else:
p=len(s)//2
t=int(s[:p+1])
if int(s[:p+1][::-1])<int(s[p:]): t+=1
while 1:
s = str(t)
res = int(s+s[:-1][::-1])
if isPrime(int(res)):
return res
else:
t+=1
s=Solution()
#print(s.primePalindrome(1))
#print(s.primePalindrome(2))
#print(s.primePalindrome(6))
#print(s.primePalindrome(8))
#print(s.primePalindrome(13))
#print(s.primePalindrome(758))
#print(s.primePalindrome(9015110))
print(s.primePalindrome(85709140))