Find the smallest prime palindrome greater than or equal to n

Quick Overview

Find the smallest integer at least n, for n up to one hundred million, that is both prime and a palindrome. It tests building palindromes directly in increasing order, pruning whole digit lengths with a divisibility argument, and keeping primality checks fast enough for nine-digit candidates.

Find the smallest prime palindrome greater than or equal to n

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

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. Note that 1 is not a prime number. An integer is a palindrome if it reads the same from left to right as it does from right to left. The answer is guaranteed to exist and to lie in the range `[2, 2 * 10^8]`. ### Function Signature ```python def prime_palindrome(n: int) -> int: ``` ### Rules - Numbers are read in base 10 without leading zeros. Every single-digit number is a palindrome. - The returned value may equal `n` itself when `n` is already a prime palindrome. ### Constraints - `1 <= n <= 10^8` ### Examples ```text Input: n = 6 Output: 7 ``` 6 is not prime, and 7 is both prime and a palindrome. ```text Input: n = 8 Output: 11 ``` 8, 9 and 10 are not prime (10 is not a palindrome either), and 11 is both. ```text Input: n = 102 Output: 131 ``` The palindromes from 102 upward are 111, 121 and 131. 111 is 3 times 37 and 121 is 11 squared, so the first prime among them is 131.

Overview: Find the smallest integer at least n, for n up to one hundred million, that is both prime and a palindrome. It tests building palindromes directly in increasing order, pruning whole digit lengths with a divisibility argument, and keeping primality checks fast enough for nine-digit candidates.

Nov 24, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

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. Note that 1 is not a prime number.

An integer is a palindrome if it reads the same from left to right as it does from right to left. The answer is guaranteed to exist and to lie in the range [2, 2 * 10^8].

Function Signature

def prime_palindrome(n: int) -> int:

Rules

  • Numbers are read in base 10 without leading zeros. Every single-digit number is a palindrome.
  • The returned value may equal n itself when n is already a prime palindrome.

Constraints

  • 1 <= n <= 10^8

Examples

Input: n = 6
Output: 7

6 is not prime, and 7 is both prime and a palindrome.

Input: n = 8
Output: 11

8, 9 and 10 are not prime (10 is not a palindrome either), and 11 is both.

Input: n = 102
Output: 131

The palindromes from 102 upward are 111, 121 and 131. 111 is 3 times 37 and 121 is 11 squared, so the first prime among them is 131.