Write an algorithm to determine if a number n is happy. A happy number is defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Constraints: 1 ≤ n ≤ 2³¹ - 1
Here is a strange process: take any positive integer, break it into its digits, square each one, and add the squares together. The result becomes your new number. Repeat.
A concrete example: start with 23. Split into digits 2 and 3. Square each: 2² = 4, 3² = 9. Sum the squares: 4 + 9 = 13. Now repeat with 13: 1² + 3² = 1 + 9 = 10. Again: 1² + 0² = 1. The chain landed on 1 — so 23 is “happy.” But not every number is so fortunate. Try 4: 4² = 16, then 1² + 6² = 37, then 9 + 49 = 58, then 25 + 64 = 89… the values keep bouncing around and never settle at 1. They cycle endlessly through the same set of values, trapped.
How would you know which fate awaits a given number without running the process until the end of time?
Before we answer that question, you need to feel the process yourself. Not by reading — by computing. Tap each digit below to square it, watch the sum form, and follow the chain wherever it leads.
Compute the digit-square-sum of 19. Tap each digit to square it.