I've got my answer working (up until a 7-digit answer is requested, anyway), and would like some help
- returning the correct answer
- speeding up the results
I was thinking of storing the values of the possible palindromes before beginning my calculations, but I know it wouldn't speed things up anyhow. I've also read around that the 'divide by 11' trick isn't always reliable (see comment #2...900009 / 11 = 81819
).
My code skims the top 10% of both the inner and outer loop before it decrements the outer loop by one, and repeats until the first result is found. This works fine, until the answer for 7-digit numbers is requested.
"""http://projecteuler.net/problem=4
Problem 4
16 November 2001
A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def main(n):
"""return the largest palindrome of products of `n` digit numbers"""
strstart = "9" * n
multic = int(strstart)
multip = multic -1
top = multic
while multic > top * .9:
while multip > multic * .9:
multip -= 1
if isPalin(multic * multip):
return multic, multip, multic*multip
multip = multic
multic -= 1
def isPalin(n):
n = str(n)
leng = len(n)
half = n[:leng/2]
if n[leng/2:] == half[::-1]:
return True
return False
if __name__ == '__main__':
main(3)
How's my approach here?