Created
October 20, 2014 21:13
-
-
Save nooodl/a543d7a204821932b13c to your computer and use it in GitHub Desktop.
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
def descending_sub_n_digit_palindromes(n): | |
while n >= 0: | |
k = (n + 1) // 2 | |
highest = 10 ** k - 1 | |
lowest = highest // 10 | |
for x in range(highest, lowest, -1): | |
s_x = str(x) # "abcde" | |
rev = s_x[::-1] # "edcba" | |
# For odd n, skip the doubled center digit: | |
if n % 2 == 1: | |
rev = rev[1:] # "dcba" | |
yield int(s_x + rev) # "abcdedcba" | |
n -= 1 | |
def find_largest_palindrome(n): | |
highest = 10 ** n - 1 | |
for p in descending_sub_n_digit_palindromes(2 * n): | |
if p > highest ** 2: | |
continue | |
for a in range(highest, int(p ** .5) - 1, -2): | |
if p % a == 0: | |
return (a, p // a) | |
def print_largest_palindrome(n): | |
a, b = find_largest_palindrome(n) | |
print('Largest palindrome found! {} x {} = {}'.format(a, b, a * b)) | |
n = int(input('How many digits in each factor? ')) | |
print_largest_palindrome(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment