LeetCode 0866. Prime Palindrome Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0866. Prime Palindrome

Description

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 * 108].

 

Example 1:

Input: n = 6
Output: 7

Example 2:

Input: n = 8
Output: 11

Example 3:

Input: n = 13
Output: 101

 

Constraints:

  • 1 <= n <= 108

Solutions

Solution 1

PythonJavaC++Go
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !