Skip to content

Instantly share code, notes, and snippets.

@rlvdx
Created December 14, 2023 08:09
Show Gist options
  • Save rlvdx/a16b8a76d3855df73e53e5eceedc8b64 to your computer and use it in GitHub Desktop.
Save rlvdx/a16b8a76d3855df73e53e5eceedc8b64 to your computer and use it in GitHub Desktop.
Find the highest palindrome resulting of the product of three three-digits integers
import time
def is_palindrome(num):
str_num = str(num)
reversed_str = str_num[::-1]
return str_num == reversed_str
max_palindrome = 0
max_a, max_b, max_c = 0, 0, 0
start_time = time.time()
for a in range(999, 99, -1):
for b in range(999, 99, -1):
for c in range(999, 99, -1):
product = a * b * c
if is_palindrome(product):
print(f"Palindrome found: {product} (a={a}, b={b}, c={c})")
if product > max_palindrome:
max_palindrome = product
max_a, max_b, max_c = a, b, c
else:
print(f"Progress: a={a}, b={b}, c={c}")
execution_time = time.time() - start_time
execution_time_str = f"Execution time: {execution_time:.3f} seconds\n"
with open("palindrome.txt", "w") as file:
file.write(f"Highest palindrome found: {max_palindrome} (a={max_a}, b={max_b}, c={max_c})\n")
file.write(execution_time_str)
print(f"Highest palindrome found: {max_palindrome} (a={max_a}, b={max_b}, c={max_c})")
print(execution_time_str)
@rlvdx
Copy link
Author

rlvdx commented Dec 14, 2023

Optimized version (based on this thread):

def is_palindrome(nr):
    rev = 0
    x = nr
    while x > 0:
        rev = 10 * rev + x % 10
        x //= 10
    return nr == rev

max_palindrome = -1

for i in range(999, 99, -1):
    for j in range(999, 99, -1):
        for k in range(999, 99, -1):
            p = i * j * k
            if max_palindrome < p and is_palindrome(p):
                max_palindrome = p
                message = f"Max palindrome is {max_palindrome}, product of {i}, {j} and {k}\n"

print(message if max_palindrome > -1 else "No palindrome found")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment