princeofsudan

ProjectEuler#4 Largest palindrome product

Mar 2nd, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers #is 9009 = 91 × 99.
  2.  
  3. #Find the largest palindrome made from the product of two 3-digit numbers.
  4.  
  5. #isPal algorithm from MIT 6.00x course notes
  6.  
  7. #Analysis
  8. #A brutish way to find the largest palindrome product of two 3-digit numbers is by searching odd factors downwards #from 999. We test each product as a palindrome and save it. Our search ends when the next product falls below the #largest palindrome found.
  9. #The two factors are printed along with their product.
  10.  
  11. def isPal(s):
  12.     if len(s) <= 1:
  13.         return True
  14.     else:
  15.         return s[0] == s[-1] and isPal(s[1:-1])
  16.  
  17.  
  18. pmax = 0
  19. for i in range(999,100,-2):
  20.   for j in range(i,100,-2):
  21.     p = i*j
  22.     if p < pmax: break
  23.     if isPal(p): x,y,pmax = i,j,p
  24.  
  25. print x,'x',y,'=',pmax
Advertisement
Add Comment
Please, Sign In to add comment