Check Happy Number in C

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Floyd cycle

What you’ll learn

  • The happy iteration: replace n by the sum of squared decimal digits until 1 or a repeat.
  • Floyd’s tortoise and hare on that map—O(1) extra memory like the reference.
  • A range scan for happy numbers in [1, 50], plus a live preview and unhappy-cycle notes.

Overview

Happy numbers are a small playground for iteration and cycle detection. The digit-square map has finite image for bounded n, so every orbit eventually cycles; Floyd detects that cycle without a hash table.

Two programs

19 classification and 1–50 listing from the reference.

Live preview

Positive safe integers; same Floyd logic as the C samples.

Rigor

Positive definition, known unhappy cycle, and why do-while matches Floyd here.

Prerequisites

Digit extraction with % 10 and /= 10, loops, and functions returning int flags.

  • #include <stdio.h>, int main(void), printf.
  • Optional: hash-set cycle detection as an alternative to Floyd.

What is a happy number?

Let f(n) be the sum of the squares of the decimal digits of n. Starting from a positive integer n, iterate n ← f(n). If you reach 1, the start was happy; otherwise you enter a cycle that never contains 1.

For 19: 82 → 68 → 100 → 1, so 19 is happy (as in the reference walkthrough).

Happy orbit hits 1
Unhappy cycle ≠ {1}
Fixed point f(1)=1

Digit map

For n = ∑ di 10i with digits di ∈ {0,…,9}, define f(n) = ∑ di2. Happy numbers are exactly those n whose forward orbit under f reaches 1.

f(19)

12 + 92 = 82, then 82 + 22 = 68, 62 + 82 = 100, 12 + 02 + 02 = 1.

Intuition

19 Happy
Path
82 → 68 → 100 → 1
2 Unhappy
Enters
4 → 16 → … cycle

Takeaway: you never need unbounded memory: either you hit 1 or you eventually repeat.

Live preview

Positive integers in the JavaScript safe range. Uses the same Floyd closure as the C code.

Try 1, 7, 2, or 23.

Live result
Press “Check happy”.

Algorithm

Goal: decide whether iterating f (sum of squared digits) reaches 1.

Implement f(n)

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

Floyd on the orbit

Maintain slow ← f(slow) and advance fast by two steps of f using fast = sum_of_squares(sum_of_squares(fast)). When they meet, meeting at 1 means happy.

📜 Pseudocode

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
1

Single value: 19

Same structure as the reference (sumOfSquares, isHappyNumber, Floyd). Renamed to sum_of_squares / is_happy and int main(void); 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;
}

Explanation

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.

2

Happy numbers in [1, 50]

Same output as the reference listing. Adds a trailing newline after the line of numbers for tidy terminals.

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

Explanation

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

Alternatives

Visited set. Store values in a hash set until repeat or 1—simple to code, O(k) memory for k orbit length.

Hard-coded cycle. Because every unhappy orbit hits the 4 → … cycle, you can return false as soon as any of those eight values appears—fast constants, less general pedagogy.

Interview: explain Floyd correctness (two speeds on a functional graph eventually meet inside the unique cycle).

❓ FAQ

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.

🔄 Input / output examples

Change number in Example 1 or the loop bounds in Example 2.

nHappy?
1Yes
7Yes
2No
19Yes

Edge cases and pitfalls

Floyd assumes the iteration is pure function on integers; any bug that mutates unrelated state can mask cycles.

n = 1

Immediate happy

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

n = 0

Not positive

Digit loop yields 0; Floyd meets at 0, not 1. Treat n < 1 separately in APIs.

Overflow

Very large n

digit*digit fits in int for decimal digits; intermediate sums stay small until n is enormous—then widen types.

Base

Other radices

Happy-base-b definitions replace decimal digits with base-b digits; results differ from base 10.

⏱️ 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.

Summary

  • Happy: iterated digit-square sums eventually hit 1.
  • Detection: Floyd’s tortoise-and-hare on f avoids storing the path.
  • Watch-outs: define behavior for n < 1; know the standard unhappy cycle.
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).

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