MediumNo. 0866

Prime Palindrome — LeetCode 866 Python Solution

Topics
Math, Number Theory
Reading time
4 min

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

PythonSolution
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 += 1

Complexity

Time
O(n) or O(1)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0858Mirror ReflectionMedium
0204Count PrimesMedium
0258Add DigitsEasy
1250Check If It Is a Good ArrayHard
1447Simplified FractionsMedium
1492The kth Factor of nMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.