Last active
December 31, 2020 03:16
-
-
Save Samin100/af3a4ce08c902badc5ef227dfc0cfda1 to your computer and use it in GitHub Desktop.
LeetCode Algorithm for https://leetcode.com/problems/largest-palindrome-product/
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 | |
for digitSize in range(1, 9): | |
print('Calculating ' + str(digitSize) + '...') | |
digits = digitSize | |
maxNum = (10 ** digits) - 1 | |
maxProd = str(maxNum * maxNum) | |
firstHalf = maxProd[0:len(maxProd) // 2] | |
found = False | |
start = time.time() | |
for x in range(int(firstHalf), 0 ,-1): # range(start, stop, step) | |
if not found: | |
palindrome = str(x) + str(x)[::-1] | |
palindrome = int(palindrome) | |
if int(palindrome) <= int(maxProd) and not found: | |
for a in range(1, int((int(palindrome) ** .5) + 1) + 1, 1): # finding factors | |
if int(palindrome) % a == 0 and int(a) <= maxNum and int(palindrome / a) <= maxNum: | |
pair = [int(a), int(palindrome / a)] | |
print('palindrome: ' + str(palindrome)) | |
print('factors under max product: ' + str(pair)) | |
found = True | |
break | |
end = time.time() | |
print('calculated in ' + str(end - start) + ' s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment