Prime Palindrome - 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. Note that 1 is not a prime number. For example, 2, 3, 5, 7, 11, and 13 are all primes.

An integer is a palindrome if it reads the same from left to right as it does from right to left. For example, 101 and 12321 are palindromes.

The test cases are generated so that the answer always exists and is in the range [2, 2 * 10⁸].

Input & Output

Example 1 — Small Number
$ Input: n = 9
Output: 11
💡 Note: Starting from 9: 9 is palindrome but not prime (divisible by 3), 10 is not palindrome, 11 is both palindrome and prime (only divisible by 1 and 11)
Example 2 — Already Prime Palindrome
$ Input: n = 2
Output: 2
💡 Note: 2 itself is both prime and palindrome, so return 2
Example 3 — Larger Input
$ Input: n = 13
Output: 101
💡 Note: 13 is prime but not palindrome. Next palindromes are 22, 33, 44, etc. but they're not prime. 101 is the first prime palindrome ≥ 13

Constraints

  • 1 ≤ n ≤ 2 × 108
  • The answer always exists and is in the range [2, 2 × 108]

Visualization

Tap to expand
Prime Palindrome Generate Palindromes Approach INPUT n = 9 Starting number Number Line 7 8 9 10 11 Start here Legend: Prime Palindrome Not Prime/Palindrome Input n ALGORITHM STEPS 1 Generate Palindromes Create palindromes by mirroring half digits 2 Check if Palindrome >= n Skip if less than input n 3 Check Primality Test if palindrome is prime using trial division 4 Return First Match Return smallest prime palindrome found Palindromes Checked: 9 --> Not Prime (3x3) 10 --> Not Palindrome 11 --> Prime + Palindrome! FINAL RESULT 11 Output Verification: Is 11 >= 9? OK Is 11 palindrome? OK Is 11 prime? OK Smallest Prime Palindrome Found! Key Insight: Instead of checking every number, generate palindromes directly! For each length, iterate through the first half of digits and mirror them. Even-length palindromes > 11 are divisible by 11, so skip them. This reduces search space dramatically compared to naive approach. Time: O(N) where N is the answer. TutorialsPoint - Prime Palindrome | Generate Palindromes Approach
Asked in
Google 15 Facebook 10 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen