Definition
Reach 1
Repeat sum of squared digits until 1 or a cycle.
A happy number reaches 1 by repeatedly summing the squares of its digits. This tutorial covers the digit map, Floyd tortoise-hare detection, a visited-set alternative, a live preview, worked Python examples, edge cases, and complexity.
Reach 1
Repeat sum of squared digits until 1 or a cycle.
Happy
19 → 82 → 68 → 100 → 1.
O(1) memory
Slow/fast pointers detect the cycle.
Starts at 4
4 → 16 → … → 20 → 4.
Try any n
Classify positive integers instantly.
Floyd steps
Tail plus cycle length in digit-sum steps.
A happy number is a positive integer that reaches 1 when you repeatedly replace it by the sum of the squares of its digits. Example: 19 → 82 → 68 → 100 → 1.
If the process never hits 1, it enters a fixed unhappy cycle (starting at 4). Floyd tortoise-hare detection finds that loop with O(1) extra memory.
It combines digit peeling with cycle detection — a clean bridge from number warm-ups to linked-list Floyd problems.
Sum of squared decimal digits.
1 is a fixed point: f(1) = 1.
Slow/fast pointers meet in a cycle.
Reject 0 and negatives by definition.
In short: keep replacing n with the sum of squared digits; if you reach 1 it is happy, otherwise you loop.
Given a positive integer n, decide whether repeated digit-square sums reach 1.
# 19 → 82 → 68 → 100 → 1 → happy
# 2 → 4 → 16 → ... cycle → unhappy
# 1 → 1 → happy | Item | Type | Description |
|---|---|---|
n | int | Positive integer (reject n < 1). |
| Return / print | bool / text | True if n is happy. |
function sum_square_digits(n):
s = 0
while n > 0:
d = n mod 10
s += d * d
n = floor(n / 10)
return s
function is_happy(n):
slow = n
fast = n
repeat:
slow = sum_square_digits(slow)
fast = sum_square_digits(sum_square_digits(fast))
until slow == fast
return slow == 1 | Method | Idea | Notes |
|---|---|---|
| Floyd | slow = f(slow), fast = f(f(fast)) | O(1) extra space — interview favorite |
| Visited set | Stop when value repeats | Clearer; uses O(k) memory |
| Known cycle | False if hit any of 4,16,… | Fast shortcut after learning the cycle |
| Goal | Pattern |
|---|---|
| Last digit | n % 10 |
| Drop digit | n //= 10 |
| Square sum | total += digit * digit |
| Floyd step | slow = f(slow); fast = f(f(fast)) |
| Happy classics | 1, 7, 19, 23 |
| Unhappy classic | 2 (enters cycle at 4) |
Three ways to decide happy vs unhappy — pick by memory and clarity.
slow / fastO(1) space; interview default
seen.add(n)Easy to explain; uses extra memory
hit 4 → falseShortcut once you know the cycle
Floyd firstThen mention the set alternative
Reach for happy-number checks when digit maps and cycles appear.
Digit loops plus cycle detection in one prompt.
Same tortoise-hare idea as linked-list cycle detection.
Print all happy numbers in 1…N for small N.
Next classic number-theory style warm-up in this chain.
State that 0 / negatives are out of scope.
Key benefit: one short boolean check that forces clear thinking about functional graphs and cycles.
Positive integers only, within JavaScript safe range.
Three complete Python programs — Floyd single check, range 1–50, and visited-set style. Click View Output to reveal sample console results.
Floyd tortoise-hare with O(1) extra memory.
19Floyd cycle detection for one value with a positive-input guard.
def sum_of_squares(n: int) -> int:
total = 0
while n > 0:
digit = n % 10
total += digit * digit
n //= 10
return total
def is_happy(n: int) -> bool:
slow = n
fast = n
while True:
slow = sum_of_squares(slow)
fast = sum_of_squares(sum_of_squares(fast))
if slow == fast:
break
return slow == 1
number = 19
if number < 1:
print("Use a positive integer.")
elif is_happy(number):
print(f"{number} is a Happy Number.")
else:
print(f"{number} is not a Happy Number.") The two pointers eventually meet. If they meet at 1, the number is happy; otherwise they met inside the unhappy cycle.
Reuse the same helper to filter a beginner interval.
Checks each number independently and prints only happy ones.
def sum_of_squares(num: int) -> int:
total = 0
while num > 0:
digit = num % 10
total += digit * digit
num //= 10
return total
def is_happy(num: int) -> bool:
slow = num
fast = num
while True:
slow = sum_of_squares(slow)
fast = sum_of_squares(sum_of_squares(fast))
if slow == fast:
break
return slow == 1
print("Happy numbers in the range 1 to 50:")
for i in range(1, 51):
if is_happy(i):
print(i, end=" ")
print() Each number uses the same happy check. Floyd keeps memory constant per check.
Easier to explain — trade O(1) space for clarity.
Stop when you hit 1 (happy) or see a repeated value (cycle).
def sum_of_squares(n: int) -> int:
total = 0
while n > 0:
digit = n % 10
total += digit * digit
n //= 10
return total
def is_happy_set(n: int) -> bool:
if n < 1:
return False
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum_of_squares(n)
return n == 1
for value in (19, 2, 1, 7):
label = "happy" if is_happy_set(value) else "unhappy"
print(f"{value}: {label}") A set records every intermediate value. Repeating a value means you entered a cycle; hitting 1 means happy. Prefer Floyd when the interviewer asks for O(1) space.
Define f(n) as the sum of squared digits.
slow = f(slow), fast = f(f(fast)).
If meeting value is 1 → happy; else cycle.
Reach 1 → yes; otherwise no.
n = 19Trace the digit-square path for the classic happy example.
| Step | n | Digit squares | Next |
|---|---|---|---|
| 1 | 19 | 12 + 92 | 82 |
| 2 | 82 | 82 + 22 | 68 |
| 3 | 68 | 62 + 82 | 100 |
| 4 | 100 | 12 + 0 + 0 | 1 |
Reached 1 → 19 is happy.
Where happy-number checks show up beyond the interview prompt.
Digit peeling plus cycle detection.
Example: write is_happy(n).
Same tortoise-hare idea as list cycles.
Example: slow/fast on f(n).
List happy numbers in a classroom interval.
Example: 1 to 50 list above.
Each n maps to exactly one next value.
Example: talk about μ and λ.
% 10 / // 10 drills before harder digit problems.
Example: before Harshad next.
All unhappy positives share one 8-cycle.
Example: start at 4.
Pro Tip: say “happy means reach 1 under digit-square iteration” before coding Floyd.
Why this pattern works well in interviews and classwork.
One sentence: reach 1 via digit-square sums.
Floyd needs no hash set for the cycle.
19 vs 2 makes verification quick.
Visited set, known cycle, and linked-list Floyd.
Pro Tip: lead with Floyd; offer a visited set if asked for the simplest version.
Small habits that keep happy-number solutions interview-ready.
Write a clean sum-of-squares helper before Floyd.
Reject n < 1 under the standard definition.
Happy and unhappy classics catch bugs fast.
Floyd meeting value is the decision signal.
Shows you understand why Floyd terminates.
Pro Tip: 1 is happy because f(1) = 1 — say that when asked about the fixed point.
Mistakes that commonly break happy-number solutions.
Using digit sum instead of digit-square sum.
→ Always square each digit.
Iterating forever on unhappy numbers.
→ Use Floyd or a visited set.
Standard definition is positive integers only.
→ Reject n < 1.
Returning true whenever pointers meet.
→ Check that the meeting value is 1.
Reusing a destroyed working variable later.
→ Keep sum_of_squares pure on a local copy.
Keep input positive and ensure the digit function is pure and deterministic.
It stays at 1.
Treat as invalid for the standard definition.
Reject negatives instead of guessing behavior.
This page uses base-10 digits only.
All unhappy positives enter the same 8-cycle.
Expect 1 7 10 13 19 23 28 31 32 44 49.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: sum squared digits repeatedly; if you reach 1 the number is happy, otherwise you loop.
| Method | Time (per check) | Extra space |
|---|---|---|
| Floyd (this page) | O(μ + λ) digit-sum steps | O(1) |
| Visited set | same step class | O(k) |
Scan [1, N] | O(N) checks | O(1) beyond each check |
μ is the tail length before the cycle; λ is the cycle length. Each digit-sum step costs O(number of digits).
Happy numbers reach 1 under repeated digit-square sums; unhappy ones enter a fixed cycle. Prefer Floyd for O(1) space, or a visited set for clarity — and always restrict to positive integers.
Practice the three examples above, then continue to Harshad numbers for another digit-sum divisibility check.
Meeting at 1 means happy; meeting elsewhere means the unhappy cycle.
Decide happiness the interview-friendly way.
Reach 1
DefinitionΣ d²
DigitsO(1) space
DetectUnhappy 8-loop
TriviaO(μ+λ)
AnalysisIf a positive integer is not happy, repeated digit-square sums enter the same unhappy cycle: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
Learn how Harshad (Niven) numbers are divisible by the sum of their digits.
9 people found this page helpful