princeofsudan

ProjectEuler#55 Lychrel numbers

Mar 29th, 2013
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. #If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
  2.  
  3. #Not all numbers produce palindromes so quickly. For example,
  4.  
  5. #349 + 943 = 1292,
  6. #1292 + 2921 = 4213
  7. #4213 + 3124 = 7337
  8.  
  9. #That is, 349 took three iterations to arrive at a palindrome.
  10.  
  11. #Although no one has proved it yet, it is thought that some numbers,
  12. #like 196, never produce a palindrome. A number that never forms a palindrome
  13. #through the reverse and add process is called a Lychrel number.
  14. #Due to the theoretical nature of these numbers, and for the purpose of
  15. #this problem, we shall assume that a number is Lychrel until proven
  16. #otherwise. In addition you are given that for every number below
  17. #ten-thousand, it will either
  18. #(i) become a palindrome in less than fifty iterations, or,
  19. #(ii) no one, with all the computing power that exists, has managed so far
  20. #to map it to a palindrome. In fact, 10677 is the first number to be shown
  21. #to require over fifty iterations before producing a palindrome:
  22. #4668731596684224866951378664 (53 iterations, 28-digits).
  23.  
  24. #Surprisingly, there are palindromic numbers that are themselves Lychrel
  25. #numbers; the first example is 4994.
  26.  
  27. #How many Lychrel numbers are there below ten-thousand?
  28.  
  29. def isPal(n):
  30.     """ Assume: n is int or str"""
  31.     if type(n) == str:
  32.         s = n
  33.     else:
  34.         s = str(n)
  35.     if len(s) <= 1:
  36.         return True
  37.     else:
  38.         return s[0] == s[-1] and isPal(s[1:-1])
  39.  
  40. def reverseAndAdd(n):
  41.     """Assume: n is int"""
  42.     return n + int(str(n)[::-1])
  43.  
  44. def isLychrel(n):
  45.     for i in range(50):
  46.         result = reverseAndAdd(n)
  47.         if isPal(result):
  48.             return False
  49.         n = result
  50.     return True    
  51.  
  52. count = 0
  53. for i in range(10000):
  54.     if isLychrel(i):
  55.         count += 1
  56. print count
Advertisement
Add Comment
Please, Sign In to add comment