princeofsudan

Project Euler #92 Square digit chains

Mar 31st, 2013
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. #A number chain is created by continuously adding the square of the digits in a number to form a new number
  2. # until it has been seen before.
  3.  
  4. #For example,
  5.  
  6. #44 > 32 > 13 > 10 > 1 > 1 (44 is called a happy number)
  7. #85 > 89 > 145 > 42 > 20 > 4 > 16 > 37 > 58 > 89
  8.  
  9. #Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop.
  10. # What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
  11.  
  12. #How many starting numbers below ten million will arrive at 89?
  13.  
  14. def isUnHappy(n):
  15.     """ Assumes n an int > 0
  16.    """
  17.     if n == 89:
  18.         return True
  19.     elif n == 1:
  20.         return False
  21.     nStr = str(n)
  22.     digitsSqrSum = 0
  23.     for digit in nStr:
  24.         digitsSqrSum += (int(digit))**2
  25.     return isUnHappy(digitsSqrSum)
  26.  
  27.  
  28.  
  29. count = 0
  30. for i in range(1,10000000):
  31.     if isUnHappy(i):
  32.         count += 1
  33. print count
Advertisement
Add Comment
Please, Sign In to add comment