AtkinsSJ

Euler 4

May 23rd, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # http://projecteuler.net/index.php?section=problems&id=4
  3.  
  4. # Find the largest numerical palindrome, made from the product of 2 3-digit numbers
  5.  
  6. # Presumably, we start with the maximum and go down until we reach a palindrome
  7.  
  8. def isPalindrome(n):
  9.     """Function that returns whether the given number is a palindrome"""
  10.     n = str(n)
  11.     length = len(n)
  12.     for i in range(length / 2):
  13.         if (n[i] != n[-i-1]):
  14.             #print n[i] + ' is not equal to ' + n[-i-1]
  15.             return False
  16.     return True
  17.  
  18. #print isPalindrome(123454321)
  19.  
  20. largest = 0
  21.  
  22. for i in range(999, 100, -1):
  23.     for j in range(i, 100, -1):
  24.         if isPalindrome(i*j):
  25.             if i*j > largest:
  26.                 largest = i*j
  27.             else:
  28.                 break
  29.  
  30. print `largest` + ' is the largest palindrome!'
  31.  
  32. # Hurrah! By starting j at i each time, and going to the
  33. # next value of i when the number isn't larger, I decreased
  34. # the execution time to nearly a third! :D
Advertisement
Add Comment
Please, Sign In to add comment