My solutions to the problems found at Project Euler.

Jump to: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 20 | 21 | 22 | 25 | 3-2 |

Problem 4


#! /usr/bin/python
#
# Problem: 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.
#

import sys
import copy

if __name__ == "__main__":
  palindromes = []
  
  # Generate a list of palindromes where we
  # can reasonable expect our answer to exist.
  for x in range(1000,500, -1):
    for y in range(999,x,-1):
      n = x*y
      n_str = str(n) # It'll be easier to work with it as a string.
      
      first_half = copy.copy(n_str[:len(n_str)/2])
      
      if len(n_str) % 2 == 0:
        second_half = copy.copy(n_str[len(n_str)/2:])
      else:
        second_half = copy.copy(n_str[len(n_str)/2+1:])
       
      first_half = list(first_half)
      second_half = list(second_half)
      second_half.reverse() 
       
      out = 'TESTING: ' + n_str + '(' + str(x) + '*' + str(y) +') - ' + '1:' + str(first_half) \
           +' 2: ' + str(second_half) + '\n'
            
      if first_half == second_half:
        palindromes.append(int(n_str))
        
  # Sort them by value and retrieve the highest one.
  palindromes.sort()
  print palindromes.pop()

jb