186k views
2 votes
Problem: Find the largest prime palindrome less than a given number.

Write a Python function largest_prime_palindrome(n) that takes an integer n as input and returns the largest prime palindrome that is less than n. A prime palindrome is a number that is both prime and a palindrome (reads the same forwards and backwards).

Your solution should be efficient and optimized for large values of n.

Here's an example of how the function should behave:

"""
>>> largest_prime_palindrome(100)
97

>>> largest_prime_palindrome(1000)
929

>>> largest_prime_palindrome(10000)
9931
"""
Note that the largest prime palindrome less than 100 is 97, less than 1000 is 929, and less than 10000 is 9931.

User Bounz
by
8.5k points

1 Answer

1 vote
Here's a Python function that takes an integer n as input and returns the largest prime palindrome that is less than n:

```python
def largest_prime_palindrome(n):
# Define a function to check if a number is prime
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True

# Define a function to check if a number is a palindrome
def is_palindrome(num):
num_str = str(num)
return num_str == num_str[::-1]

# Loop through all numbers less than n in reverse order
for num in range(n - 1, 0, -1):
if is_prime(num) and is_palindrome(num):
return num

# If no prime palindrome is found, return None
return None
```

The function first defines two helper functions, `is_prime` and `is_palindrome`, to check if a number is prime and if it is a palindrome, respectively. It then loops through all numbers less than n in reverse order, checking if each number is both prime and a palindrome. If it finds a number that meets both criteria, it returns that number. If it doesn't find any prime palindromes, it returns `None`.

This solution should be efficient for large valuesof n because it checks for palindromes and primes separately and in the most efficient way possible. Checking for primes requires iterating through numbers up to the square root of the number being tested, and checking for palindromes just requires converting the number to a string and comparing it to its reverse. The function also uses the fact that the largest prime palindrome less than n must be less than n, so it loops through numbers in reverse order to find the largest one that meets both criteria.
User Lanesha
by
7.6k points