Prime Palindrome — LeetCode 866 Python Solution
- Problem
- #866
- Pattern
- Math and Number Theory
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given an integer n, return the smallest prime palindrome greater than or equal to n. An integer is prime if it has exactly two divisors: 1 and itself.
Example
- Input
- n = 6
- Output
- 7
Python solution
class Solution:
def primePalindrome(self, n: int) -> int:
def is_prime(x):
if x < 2:
return False
v = 2
while v * v <= x:
if x % v == 0:
return False
v += 1
return True
def reverse(x):
res = 0
while x:
res = res * 10 + x % 10
x //= 10
return res
while 1:
if reverse(n) == n and is_prime(n):
return n
if 10**7 < n < 10**8:
n = 10**8
n += 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 866. Prime Palindrome is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Number Theory.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 866. Prime Palindrome?
- LeetCode 866. Prime Palindrome is rated Medium on LeetCode.
- What topics does LeetCode 866. Prime Palindrome cover?
- LeetCode 866. Prime Palindrome is tagged Math and Number Theory on LeetCode.