Definition
Orbit to 1
Replace n by the sum of squared digits; happy if you reach 1.
Happy numbers are a classic interview warm-up: digit extraction, iteration, and cycle detection. This tutorial covers the digit-square map, Floyd’s tortoise-and-hare, a live preview, algorithm steps, worked C examples, edge cases, and complexity.
Orbit to 1
Replace n by the sum of squared digits; happy if you reach 1.
Σ di²
Peel digits with % 10, square, accumulate, divide by 10.
O(1) space
Tortoise and hare meet at 1 (happy) or another cycle (unhappy).
4 → …
Every non-happy orbit eventually enters the known 8-value cycle.
Check n
Classify any positive safe integer instantly in the browser.
1–50
List all happy numbers in a closed interval with the same helper.
Happy numbers start from a positive integer n. Repeatedly replace n by the sum of the squares of its decimal digits. If the process reaches 1, n is happy; otherwise it enters a cycle that never contains 1.
In C interviews you are usually asked to implement the digit-square map, detect cycles with Floyd’s tortoise and hare (O(1) extra memory), and optionally list happy numbers in a range.
It trains digit loops, functional-graph thinking, and cycle detection without a hash table — skills that transfer to linked-list cycles and other orbit problems.
The fixed point f(1) = 1 ends a happy orbit.
Two speeds on f; meet at 1 means happy.
All non-happy orbits share one 8-value loop.
Standard definition uses positive integers.
In short: iterate sum-of-squared-digits; if Floyd’s pointers meet at 1, the number is happy — otherwise it entered a non-1 cycle.
Given a positive integer n, decide whether iterating the sum of squared decimal digits eventually reaches 1.
/* Happy path for 19
* 19 → 1²+9² = 82
* 82 → 8²+2² = 68
* 68 → 6²+8² = 100
* 100 → 1²+0²+0² = 1 → happy
*/ | Item | Type | Description |
|---|---|---|
n / number | int | Positive integer to classify (Example 1). |
| Range bounds | int | Inclusive interval such as [1, 50] (Example 2). |
| Result | flag / text | Happy or not; or a printed list of happy values. |
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 | Extra space |
|---|---|---|
| Floyd (this page) | Slow = one f step; fast = two f steps | O(1) |
| Visited set | Store every orbit value until repeat or 1 | O(k) for orbit length k |
| Goal | Pattern |
|---|---|
| Next digit square sum | digit = n % 10; sum += digit * digit; n /= 10; |
| Slow step | slow = sum_of_squares(slow); |
| Fast step | fast = sum_of_squares(sum_of_squares(fast)); |
| Happy test | return slow == 1; after pointers meet |
| Reject non-positive | if (number < 1) { … } |
All can classify happy numbers — memory and pedagogy differ.
tortoise/hareO(1) space; interview-friendly cycle story
visitedSimple to write; uses O(k) memory
hit 4?Fast once you know the cycle; less general
explain FloydTwo speeds meet inside the unique cycle
Reach for happy-number drills when digit maps and cycles matter.
Digit loops plus a clear cycle-detection story.
Same tortoise-and-hare idea as linked-list cycle detection.
Each n has one successor under f — orbits end in cycles.
List or count happy numbers in [L, R].
Happy-in-base-b uses different digits — results change.
Key benefit: one small problem that covers digits, iteration, and O(1)-space cycle detection together.
Enter a positive integer and classify it with the same Floyd logic as the C samples.
Two complete C programs — classify a single value, and list happy numbers in [1, 50]. Click View Output to reveal sample console results.
Floyd cycle detection for n = 19.
19Digit-square helper plus tortoise-and-hare; rejects n < 1 in main.
#include <stdio.h>
int sum_of_squares(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
int is_happy(int n) {
int slow = n;
int fast = n;
do {
slow = sum_of_squares(slow);
fast = sum_of_squares(sum_of_squares(fast));
} while (slow != fast);
return slow == 1;
}
int main(void) {
int number = 19;
if (number < 1) {
printf("Use a positive integer.\n");
return 0;
}
if (is_happy(number)) {
printf("%d is a Happy Number.\n", number);
} else {
printf("%d is not a Happy Number.\n", number);
}
return 0;
} The do-while performs at least one advance so n = 1 is classified immediately: both pointers read 1 and the loop stops with slow == 1.
Reuse the same helper across a closed interval.
[1, 50]Scan each i independently; Floyd keeps extra memory O(1) per check.
#include <stdio.h>
int sum_of_squares(int num) {
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
return sum;
}
int is_happy(int num) {
int slow = num;
int fast = num;
do {
slow = sum_of_squares(slow);
fast = sum_of_squares(sum_of_squares(fast));
} while (slow != fast);
return slow == 1;
}
int main(void) {
int i;
printf("Happy numbers in the range 1 to 50:\n");
for (i = 1; i <= 50; ++i) {
if (is_happy(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
} Each i is tested independently; the happy test stays O(1) extra memory per call thanks to Floyd.
Require a positive integer; happy numbers are not defined for n < 1 here.
Sum the squares of decimal digits with % 10 and /= 10.
Advance slow by one f step and fast by two until they meet.
Meeting at 1 → happy; otherwise → unhappy cycle.
19Trace the digit-square orbit until it reaches the fixed point 1.
| Step | Value | Digit squares | Next |
|---|---|---|---|
0 | 19 | 1² + 9² | 82 |
1 | 82 | 8² + 2² | 68 |
2 | 68 | 6² + 8² | 100 |
3 | 100 | 1² + 0² + 0² | 1 |
4 | 1 | 1² | 1 (happy) |
By contrast, 2 eventually enters 4 → 16 → 37 → … → 4 and never hits 1.
Where happy-number thinking shows up beyond the interview prompt.
Same tortoise-and-hare idea as linked-list cycles.
Example: meet inside the unique orbit cycle.
Build fluency with % 10 / /= 10 loops.
Example: sum-of-squares helper reused elsewhere.
Each value has one successor — orbits end in cycles.
Example: happy sink vs unhappy 8-cycle.
List or count numbers with a property in [L, R].
Example: happy numbers in 1–50.
Compare Floyd vs storing a visited set.
Example: O(1) vs O(k) extra space.
Harshad, Disarium, and similar digit-sum problems.
Example: next pages in the interview chain.
Pro Tip: if the interviewer allows constants, mentioning the unhappy cycle is fine — but Floyd shows you understand general cycle detection.
Why Floyd on the digit-square map earns interview points.
No hash set of visited values — only two integers on the orbit.
Two speeds on a functional graph must meet inside the unique cycle.
sum_of_squares + is_happy is easy to test and reuse in a range scan.
A do-while Floyd loop classifies the fixed point without special cases.
Pro Tip: lead with Floyd; mention the unhappy cycle as optional constant-time early exit if asked about optimizations.
Small habits that keep happy-number code clean in interviews.
Validate n ≥ 1 in main (or your API) before calling is_happy.
Guarantees one advance so n = 1 works without a special branch.
sum_of_squares should only depend on its argument — Floyd assumes a pure map.
Verify 1, 7, 19 (happy) and 2, 4 (unhappy).
Call the same is_happy from a loop — do not re-inline Floyd each time.
Pro Tip: dry-run 19 on paper (table above) before coding — it locks in the digit-square path.
Mistakes that commonly break happy-number solutions in C.
A bare while (n != 1) loop never stops on unhappy numbers.
→ Use Floyd, a visited set, or the known unhappy cycle.
Checking slow != fast before any move can mishandle n = 1.
→ Prefer do { … } while (slow != fast);
0 yields a fixed point at 0, which is not happy under the usual definition.
→ Reject non-positive inputs in the API.
If f is not pure, Floyd can miss or invent cycles.
→ Keep sum_of_squares a pure function of n.
Happy-in-base-b is a different problem from base-10 happy numbers.
→ Confirm the radix with the interviewer.
Check these inputs before calling the solution done.
The do-while still runs one round; both pointers land on 1.
Digit loop yields 0; treat n < 1 separately in APIs.
n = 2 or 4Enters the standard cycle; Floyd meets at a value other than 1.
digit*digit fits in int for decimal digits; widen types if needed.
Standard happy numbers are positive; reject or normalize explicitly.
Happy-base-b replaces decimal digits — results differ.
Known classifications for common interview inputs.
n | Happy? |
|---|---|
1 | Yes |
7 | Yes |
2 | No |
19 | Yes |
Try these variations to lock in the pattern.
scanf and validate n ≥ 11[L, R]is_happy4 → 16 → … → 4.1 is the happy test.n ≥ 1; n = 1 is happy by the fixed-point definition.int inputs, orbit lengths stay small — complexity is effectively constant in practice.Quick Takeaway: iterate sum-of-squared-digits; Floyd meets at 1 for happy numbers, otherwise at the unhappy cycle — all in O(1) extra space.
| Method | Time (per check) | Extra space |
|---|---|---|
| Floyd (this page) | O(μ + λ) digit-squaring steps | O(1) |
| Hash set of visited values | same asymptotic steps | O(k) for orbit length k |
Scan [1, N] | O(N) checks | O(1) beyond each check |
Here μ is the tail length before the cycle and λ the cycle length under f.
Happy numbers are a small digit-iteration exercise with big teaching payoff: pure maps, orbits, and O(1)-space cycle detection. Master Floyd on the digit-square function so you can explain both the happy path and the unhappy cycle in an interview.
Practice the two examples above, then continue to Harshad numbers for another digit-sum property check.
Iterate sum-of-squared-digits; Floyd meets at 1 for happy numbers — validate n ≥ 1 and know the unhappy cycle.
do-while so n = 1 worksn ≥ 1 at the API boundarysum_of_squares puren == 1 without cycle detection0 or negatives without a defined policy2Classify them the interview-friendly way.
Orbit hits 1
DefinitionSum of digit²
DigitsO(1) cycle detect
CodeShared 8-cycle
FactO(μ+λ) steps
AnalysisIf a positive integer is not happy, iterating digit-square sums always falls into the same unhappy cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 (so Floyd’s detection need not store the whole path).
Learn how to check whether a number is divisible by the sum of its digits.
8 people found this page helpful