pythonnumbershappy

Program for happy numbers


So the happy number is a number, where starting with any positive integers replace the number by the sum of squares of its digits, this process will be repeated until it becomes 1, otherwise, it will loop endlessly in a cycle. Those numbers, when the 1 has found, they will be a happy number.

Suppose the number is 19, the output will be true as the number is a happy number. As we can see from 19, we will get

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1

Here is my code:

def happy(n):
  s = list(str(n))
  sum = 0
  for i in s:
      sum += int(i)**2
  if sum == 1:
    return True
  else:
    happy(sum)
      

    
    

x = 0
if __name__=="__main__":
    n =int(input())
    print(happy(n)) # to check what it returns
    if happy(n):
      print("True")
    else:
      print("False")

since 19 is a happy number but my function always returns None instead of True. Why so?


Solution

  • The only problem is that the program will be stuck if you try with a non-happy number (like 58) that will keep looping. Another way is to loop until the result is one-digit long and verify if it's 1.

    Note that you can use a while loop instead of recursion to avoid getting a RecursionError.

    def happy(n):
        while len(str(n)) > 1:
            n = sum(int(x)**2 for x in str(n))
        return n == 1