Happy Numbers

Check if number is happy number.

Logic BuildingAdvanced
Logic Building
def sum_square_digits(n):
    total = 0
    while n > 0:
        digit = n % 10
        total += digit * digit
        n //= 10
    return total

def is_happy(n):
    seen = set()
    while n != 1 and n not in seen:
        seen.add(n)
        n = sum_square_digits(n)
    return n == 1

# Test
num = int(input("Enter a number: "))
if is_happy(num):
    print("Happy number")
else:
    print("Not a happy number")

Output

Enter a number: 19
Happy number

Happy number: eventually reaches 1 by summing squares of digits.

Key Concepts:

  • Sum squares of digits repeatedly
  • Track seen numbers to detect cycle
  • Returns True if reaches 1