Created
December 14, 2023 08:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Optimized version (based on this thread):