Given an integer n
, find the smallest prime palindrome greater than or equal to n
.
You need to write a function prime_palindrome(n: int) -> int
that returns the smallest prime palindrome greater than or equal to n
.
n
?
1 <= n <= 10^8
.To solve this problem, the following steps can be followed:
n
, iterate the numbers upwards until a number is found that is both prime and a palindrome.We’ll create a function is_prime
that uses trial-division to determine if a number is prime.
We’ll create a function is_palindrome
to check if a number reads the same forward and backward.
Using a loop starting from n
, use both helper functions to find the smallest prime palindrome.
O(sqrt(n))
O(d)
where d
is the number of digits in n
def prime_palindrome(n: int) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
for i in range(2, int(x**0.5) + 1):
if x % i == 0:
return False
return True
def is_palindrome(x: int) -> bool:
return str(x) == str(x)[::-1]
# Palindrome generation can be more optimal but let's begin simple and correct
while True:
if is_palindrome(n) and is_prime(n):
return n
n += 1
# Let's test the provided function
print(prime_palindrome(6)) # Expected output: 7
print(prime_palindrome(8)) # Expected output: 11
print(prime_palindrome(13)) # Expected output: 101
# Note: Further optimization like skipping even-length palindromes can be added.
This initial solution will work correctly needs testing for performance to ensure it runs efficiently for larger values of n
. Further steps will involve optimizing palindrome generation and skipping certain non-palindromic ranges intelligently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?