Check Happy Number in C

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 2 Code Examples
🚀 Live Preview
Floyd cycle

What You’ll Learn

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.

Definition

Orbit to 1

Replace n by the sum of squared digits; happy if you reach 1.

Digit Map f(n)

Σ di²

Peel digits with % 10, square, accumulate, divide by 10.

Floyd

O(1) space

Tortoise and hare meet at 1 (happy) or another cycle (unhappy).

Unhappy Cycle

4 → …

Every non-happy orbit eventually enters the known 8-value cycle.

Live Preview

Check n

Classify any positive safe integer instantly in the browser.

Range Scan

1–50

List all happy numbers in a closed interval with the same helper.

Introduction

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.

Why it matters?

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.

Key Highlights

Happy ↔ Hits 1

The fixed point f(1) = 1 ends a happy orbit.

Floyd Detection

Two speeds on f; meet at 1 means happy.

Known Unhappy Cycle

All non-happy orbits share one 8-value loop.

Positive Only

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.

📝 Problem & Approach

Given a positive integer n, decide whether iterating the sum of squared decimal digits eventually reaches 1.

c
/* Happy path for 19
 * 19 → 1²+9² = 82
 * 82 → 8²+2² = 68
 * 68 → 6²+8² = 100
 * 100 → 1²+0²+0² = 1  → happy
 */

Inputs & Outputs

ItemTypeDescription
n / numberintPositive integer to classify (Example 1).
Range boundsintInclusive interval such as [1, 50] (Example 2).
Resultflag / textHappy or not; or a printed list of happy values.

Minimal workflow

Pseudocode
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 comparison

MethodIdeaExtra space
Floyd (this page)Slow = one f step; fast = two f stepsO(1)
Visited setStore every orbit value until repeat or 1O(k) for orbit length k

⚡ Quick Reference

GoalPattern
Next digit square sumdigit = n % 10; sum += digit * digit; n /= 10;
Slow stepslow = sum_of_squares(slow);
Fast stepfast = sum_of_squares(sum_of_squares(fast));
Happy testreturn slow == 1; after pointers meet
Reject non-positiveif (number < 1) { … }

📋 Floyd vs Hash Set vs Hard-Coded Cycle

All can classify happy numbers — memory and pedagogy differ.

Floyd
tortoise/hare

O(1) space; interview-friendly cycle story

Hash set
visited

Simple to write; uses O(k) memory

Unhappy constants
hit 4?

Fast once you know the cycle; less general

Interview tip
explain Floyd

Two speeds meet inside the unique cycle

Context

When This Problem Shows Up

Reach for happy-number drills when digit maps and cycles matter.

  1. Interview warm-ups

    Digit loops plus a clear cycle-detection story.

  2. Teaching Floyd

    Same tortoise-and-hare idea as linked-list cycle detection.

  3. Functional graphs

    Each n has one successor under f — orbits end in cycles.

  4. Range / filter tasks

    List or count happy numbers in [L, R].

  5. Not for other bases blindly

    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.

🔮 Live Preview

Enter a positive integer and classify it with the same Floyd logic as the C samples.

Try 1, 7, 2, or 23.

Live result
Press “Check happy”.

Examples Gallery

Two complete C programs — classify a single value, and list happy numbers in [1, 50]. Click View Output to reveal sample console results.

📚 Getting Started

Floyd cycle detection for n = 19.

Example 1 — Single Value: 19

Digit-square helper plus tortoise-and-hare; rejects n < 1 in main.

c
#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;
}

How It Works

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.

📈 Practical Patterns

Reuse the same helper across a closed interval.

Example 2 — Happy Numbers in [1, 50]

Scan each i independently; Floyd keeps extra memory O(1) per check.

c
#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;
}

How It Works

Each i is tested independently; the happy test stays O(1) extra memory per call thanks to Floyd.

🧠 How the Algorithm Classifies n

1

Validate n

Require a positive integer; happy numbers are not defined for n < 1 here.

Guard
2

Compute f(n)

Sum the squares of decimal digits with % 10 and /= 10.

Map
3

Run Floyd

Advance slow by one f step and fast by two until they meet.

Cycle
=

Decide

Meeting at 1 → happy; otherwise → unhappy cycle.

🔎 Worked Walkthrough — 19

Trace the digit-square orbit until it reaches the fixed point 1.

StepValueDigit squaresNext
0191² + 9²82
1828² + 2²68
2686² + 8²100
31001² + 0² + 0²1
411 (happy)

By contrast, 2 eventually enters 4 → 16 → 37 → … → 4 and never hits 1.

Use Cases

Where happy-number thinking shows up beyond the interview prompt.

1. Cycle Detection Practice

Same tortoise-and-hare idea as linked-list cycles.

Example: meet inside the unique orbit cycle.

2. Digit Extraction Drills

Build fluency with % 10 / /= 10 loops.

Example: sum-of-squares helper reused elsewhere.

3. Functional Graphs

Each value has one successor — orbits end in cycles.

Example: happy sink vs unhappy 8-cycle.

4. Range Filters

List or count numbers with a property in [L, R].

Example: happy numbers in 1–50.

5. Memory Trade-offs

Compare Floyd vs storing a visited set.

Example: O(1) vs O(k) extra space.

6. Related Digit Properties

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.

Advantages

Why Floyd on the digit-square map earns interview points.

  1. 1. O(1) Extra Memory

    No hash set of visited values — only two integers on the orbit.

  2. 2. Clear Correctness Story

    Two speeds on a functional graph must meet inside the unique cycle.

  3. 3. Tiny Helper Surface

    sum_of_squares + is_happy is easy to test and reuse in a range scan.

  4. 4. Handles n = 1 Cleanly

    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.

Usage Tips

Small habits that keep happy-number code clean in interviews.

  1. 1. Restrict to Positive n

    Validate n ≥ 1 in main (or your API) before calling is_happy.

  2. 2. Prefer do-while for Floyd

    Guarantees one advance so n = 1 works without a special branch.

  3. 3. Keep Helpers Pure

    sum_of_squares should only depend on its argument — Floyd assumes a pure map.

  4. 4. Test Happy and Unhappy

    Verify 1, 7, 19 (happy) and 2, 4 (unhappy).

  5. 5. Reuse for Ranges

    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.

Common Pitfalls

Mistakes that commonly break happy-number solutions in C.

  1. 1. Skipping Cycle Detection

    A bare while (n != 1) loop never stops on unhappy numbers.

    → Use Floyd, a visited set, or the known unhappy cycle.

  2. 2. While Instead of do-while

    Checking slow != fast before any move can mishandle n = 1.

    → Prefer do { … } while (slow != fast);

  3. 3. Accepting n < 1 Silently

    0 yields a fixed point at 0, which is not happy under the usual definition.

    → Reject non-positive inputs in the API.

  4. 4. Mutating Shared State

    If f is not pure, Floyd can miss or invent cycles.

    → Keep sum_of_squares a pure function of n.

  5. 5. Confusing Bases

    Happy-in-base-b is a different problem from base-10 happy numbers.

    → Confirm the radix with the interviewer.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Immediate happy

The do-while still runs one round; both pointers land on 1.

n = 0

Not positive

Digit loop yields 0; treat n < 1 separately in APIs.

Unhappy

n = 2 or 4

Enters the standard cycle; Floyd meets at a value other than 1.

Overflow

Very large n

digit*digit fits in int for decimal digits; widen types if needed.

Negatives

Out of scope

Standard happy numbers are positive; reject or normalize explicitly.

Base

Other radices

Happy-base-b replaces decimal digits — results differ.

🔄 Sample Values

Known classifications for common interview inputs.

nHappy?
1Yes
7Yes
2No
19Yes

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Read n from stdin

  • Use scanf and validate n ≥ 1
  • Print a clear happy / not-happy message

2. Visited-set variant

  • Store orbit values until repeat or 1
  • Compare space with Floyd

3. Count in a range

  • Return how many happy numbers lie in [L, R]
  • Reuse is_happy

4. Early exit on cycle 4

  • Return false as soon as any unhappy-cycle value appears
  • Discuss trade-off vs general Floyd

Notes

  • Unhappy cycle. Every non-happy positive integer eventually hits 4 → 16 → … → 4.
  • Floyd needs no path storage — meeting at 1 is the happy test.
  • Validate n ≥ 1; n = 1 is happy by the fixed-point definition.
  • For bounded 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.

⏱️ Time and Space Complexity

MethodTime (per check)Extra space
Floyd (this page)O(μ + λ) digit-squaring stepsO(1)
Hash set of visited valuessame asymptotic stepsO(k) for orbit length k
Scan [1, N]O(N) checksO(1) beyond each check

Here μ is the tail length before the cycle and λ the cycle length under f.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • Explain the digit-square map before coding Floyd
  • Use do-while so n = 1 works
  • Validate n ≥ 1 at the API boundary
  • Keep sum_of_squares pure
  • Mention the unhappy cycle as optional knowledge

❌ Don’t

  • Loop until n == 1 without cycle detection
  • Accept 0 or negatives without a defined policy
  • Store the whole path when O(1) Floyd works
  • Forget to test an unhappy example like 2
  • Assume another base without clarifying

Key Takeaways

Knowledge Unlocked

Five things to remember about happy numbers in C

Classify them the interview-friendly way.

5
Core concepts
Σ 02

Map f(n)

Sum of digit²

Digits
F 03

Floyd

O(1) cycle detect

Code
4 04

Unhappy

Shared 8-cycle

Fact
O 05

Complexity

O(μ+λ) steps

Analysis

❓ Frequently Asked Questions

Start with a positive integer n. Repeatedly replace n by the sum of the squares of its decimal digits. If you eventually reach 1, n is happy; otherwise the process enters a cycle that never hits 1.
Yes. The sum of squared digits of 1 is 1, so the process terminates immediately at the fixed point 1.
The naive approach stores every visited value in a hash set. Floyd's tortoise-and-hare uses O(1) extra memory: two pointers advance through the iteration at different speeds; meeting with value 1 means happy, meeting otherwise means a non-1 cycle.
In the digit loop, while n > 0 yields sum 0 for n = 0. For happy checks, restrict to positive n in main so the interpretation is clear.
Happy numbers are defined for positive integers. Squaring digits of -19 matches 19 in magnitude only if you normalize to absolute value first; this page keeps the interface nonnegative.
Each digit-sum step costs O(log n) digit operations in base 10. Floyd terminates in O(μ + λ) such steps where μ is the tail length and λ the cycle length—constants bounded for 32-bit int inputs in practice.
Every non-happy positive integer eventually enters 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. Seeing any of those values proves unhappiness.
A do-while performs at least one advance so n = 1 is classified correctly: both pointers land on 1 and stop with slow == 1.

Did you Know? 🔊

If 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).

Continue to Harshad Number

Learn how to check whether a number is divisible by the sum of its digits.

Harshad tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful