Last active
August 29, 2015 14:10
-
-
Save ebartrum/88c3e32450ccd3179eab to your computer and use it in GitHub Desktop.
A solution to the 4th Euler Challenge
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
"""A palindromic number reads the same both ways. Find the | |
largest palindrome made from the product of two 3-digit numbers.""" | |
#Define a 'surround' function that will be used to construct palindromes | |
def surround(x,y): | |
x=str(x) | |
y=str(y) | |
return str((y+x+y)) | |
#start with an initial array of all palidromes of length 1 or 2 | |
initialArray=['0','1','2','3','4','5','6','7','8','9','00','11','22','33','44','55','66','77','88','99'] | |
#Now build an array of palindromes less than 1000000 | |
k=1 | |
while k<3: | |
array=[] | |
j=0 | |
while j<10: | |
for i in initialArray: | |
array.append(surround(i,str(j))) | |
j+=1 | |
for x in array: | |
initialArray.append(x) | |
k+=1 | |
#Get rid of strings with leading zeroes | |
def removeLeadingZeroes(x): | |
ans=[] | |
for y in x: | |
if y[0]!='0' or y=='0': | |
ans.append(y) | |
return ans | |
array=array+initialArray | |
array=removeLeadingZeroes(array) | |
#convert to an array of integers, remove any duplicates, and sort into descending order | |
def convertToInts(x): | |
ans=[] | |
for y in x: | |
z=int(y) | |
ans.append(z) | |
return ans | |
array=list(set(array)) | |
array=convertToInts(array) | |
array=sorted(array) | |
array.reverse() | |
def factor(x): | |
z=[] | |
i=1 | |
while (i<=x): | |
if x%i==0: | |
z.append(i) | |
i+=1 | |
return z | |
#Define a test of the 3 digit product condition | |
def threeDigitTest(x): | |
ans=False | |
y=factor(x) | |
for z in y: | |
if (len(str(int(x/z)))==3 and len(str(z))==3): | |
ans=True | |
return ans | |
#now search through the array for first element that passes test. | |
i=0 | |
found=False | |
while found==False: | |
if threeDigitTest(array[i]): | |
ans=array[i] | |
found=True | |
else: | |
i+=1 | |
print(ans) | |
#The answer is 906609 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment