A positive integer is a happy number if repeatedly replacing it with the sum of the squares of its digits eventually reaches 1. If the process loops without hitting 1, the number is unhappy.
Four clear steps — then pick a visited array or Floyd’s tortoise and hare.
Require $n > 0 (positive integers only).
Define f(n) = sum of squares of digits of n.
Keep applying f until you reach 1 (happy) or detect a repeat (unhappy).
Detect repeats with a visited array, or use Floyd cycle detection for O(1) extra space.
Method
Idea
Extra space
Best for
Visited array
Stop when a value repeats
O(k)
Clarity, first solution
Floyd
slow = f(slow), fast = f(f(fast))
O(1)
Interviews, memory limits
Pseudocode
Pseudocode
function SumOfSquares(n):
total = 0
while n > 0:
d = n mod 10
total = total + d * d
n = floor(n / 10)
return total
function IsHappy(n):
if n <= 0:
return false
seen = empty set
while n != 1 and n not in seen:
add n to seen
n = SumOfSquares(n)
return n == 1
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Core step
$total += ($n % 10) ** 2; $n = intdiv($n, 10);
Happy when
Chain reaches 1
Unhappy when
A value repeats before 1
Known cycle
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
Floyd move
$slow = f($slow); $fast = f(f($fast));
Classic happy
1, 7, 10, 13, 19, 23
Classic unhappy
2, 4, 5, 16
Try it
Live Preview
Enter a positive integer to see the digit-square chain and the happy/unhappy verdict.
Positive whole numbers only. Tap a chip or type a value.
Result
n = 19
Chain: 19 → 82 → 68 → 100 → 1
Verdict: HAPPY NUMBER
Trace
Worked Walkthrough — n = 19
Square each digit, sum, and replace until you hit 1.