Skip to content

Commit 88bf88b

Browse files
committed
Create prime-palindrome.py
1 parent f016299 commit 88bf88b

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Python/prime-palindrome.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Time: O(n^(3/2))
2+
# Space: O(logn)
3+
4+
# Find the smallest prime palindrome greater than or equal to N.
5+
# Recall that a number is prime if it's only divisors are 1 and itself,
6+
# and it is greater than 1.
7+
#
8+
# For example, 2,3,5,7,11 and 13 are primes.
9+
#
10+
# Recall that a number is a palindrome if it reads the same from
11+
# left to right as it does from right to left.
12+
#
13+
# For example, 12321 is a palindrome.
14+
#
15+
# Example 1:
16+
#
17+
# Input: 6
18+
# Output: 7
19+
# Example 2:
20+
#
21+
# Input: 8
22+
# Output: 11
23+
# Example 3:
24+
#
25+
# Input: 13
26+
# Output: 101
27+
#
28+
# Note:
29+
# - 1 <= N <= 10^8
30+
# - The answer is guaranteed to exist and be less than 2 * 10^8.
31+
32+
try:
33+
xrange # Python 2
34+
except NameError:
35+
xrange = range # Python 3
36+
37+
38+
class Solution(object):
39+
def primePalindrome(self, N):
40+
"""
41+
:type N: int
42+
:rtype: int
43+
"""
44+
def is_prime(n):
45+
if n < 2 or n % 2 == 0:
46+
return n == 2
47+
return all(n % d for d in xrange(3, int(n**.5) + 1, 2))
48+
49+
if 8 <= N <= 11:
50+
return 11
51+
for i in xrange(10**(len(str(N))//2), 10**5):
52+
j = int(str(i) + str(i)[-2::-1])
53+
if j >= N and is_prime(j):
54+
return j

0 commit comments

Comments
 (0)