C# Happy Number Program

Beginner
7 min read
Updated: Oct 2026
2 programs
Live preview

What Is a Happy Number?

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.

Remember
n is happy  ⇔  digit-square chain reaches 1

Example: 19
  1² + 9² = 82
  8² + 2² = 68
  6² + 8² = 100
  1² + 0² + 0² = 1   ← happy

Unhappy numbers enter:
  4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
nChain (short)Result
1already 1Happy
77 → … → 1Happy
1919 → 82 → 68 → 100 → 1Happy
22 → 4 → (cycle)Unhappy

How to Check a Happy Number in C#

Four clear steps — then pick a visited set or Floyd’s tortoise and hare.

  1. Require n > 0 (positive integers only).
  2. Define f(n) = sum of squares of digits of n.
  3. Keep applying f until you reach 1 (happy) or detect a repeat (unhappy).
  4. Detect repeats with a HashSet, or use Floyd cycle detection for O(1) extra space.
MethodIdeaExtra spaceBest for
Visited setStop when a value repeatsO(k)Clarity, first solution
Floydslow = 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 = 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

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Core steptotal += (n % 10) * (n % 10); n /= 10
Happy whenChain reaches 1
Unhappy whenA value repeats before 1
Known cycle4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
Floyd moveslow = f(slow); fast = f(f(fast))
Classic happy1, 7, 10, 13, 19, 23
Classic unhappy2, 4, 5, 16

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

Worked Walkthrough — n = 19

Square each digit, sum, and replace until you hit 1.

Calculation
Step 1: 1² + 9² = 1 + 81 = 82
Step 2: 8² + 2² = 64 + 4  = 68
Step 3: 6² + 8² = 36 + 64 = 100
Step 4: 1² + 0² + 0² = 1

Reached 1 → 19 is happy

C# Programs

Start with a visited set so the stop condition is obvious. Then use Floyd’s cycle detection when you want O(1) extra space.

Example 1 — Visited HashSet

Store every value you produce. Reach 1 → happy; see a repeat → unhappy.

C#
using System;
using System.Collections.Generic;

class Program
{
    static int SumOfSquares(int n)
    {
        int total = 0;
        while (n > 0)
        {
            int d = n % 10;
            total += d * d;
            n /= 10;
        }
        return total;
    }

    static bool IsHappy(int n)
    {
        if (n <= 0)
        {
            return false;
        }

        HashSet<int> seen = new HashSet<int>();
        while (n != 1 && !seen.Contains(n))
        {
            seen.Add(n);
            n = SumOfSquares(n);
        }
        return n == 1;
    }

    static void Main()
    {
        int number = 19;
        if (IsHappy(number))
        {
            Console.WriteLine(number + " is a Happy Number.");
        }
        else
        {
            Console.WriteLine(number + " is not a Happy Number.");
        }
    }
}

How It Works

  1. SumOfSquares peels digits with % 10 and adds each square.
  2. Reject n <= 0 so only positive integers are checked.
  3. While n is not 1 and has not been seen, add it to seen and replace with SumOfSquares(n).
  4. If n becomes 1, return true.
  5. If n reappears in seen, you hit a cycle — return false.

Example 2 — Floyd Cycle Detection

Move a slow pointer one step and a fast pointer two steps. Meeting at 1 means happy.

C#
using System;

class Program
{
    static int SumOfSquares(int n)
    {
        int total = 0;
        while (n > 0)
        {
            int d = n % 10;
            total += d * d;
            n /= 10;
        }
        return total;
    }

    static bool IsHappy(int n)
    {
        if (n <= 0)
        {
            return false;
        }

        int slow = n;
        int fast = SumOfSquares(n);

        while (fast != 1 && slow != fast)
        {
            slow = SumOfSquares(slow);
            fast = SumOfSquares(SumOfSquares(fast));
        }

        return fast == 1;
    }

    static void Main()
    {
        Console.WriteLine(IsHappy(19) ? "19 is happy" : "19 is unhappy");
        Console.WriteLine(IsHappy(2) ? "2 is happy" : "2 is unhappy");
        Console.WriteLine(IsHappy(7) ? "7 is happy" : "7 is unhappy");
    }
}

How It Works

  1. Reuse the same SumOfSquares helper as the set version.
  2. slow advances one application of f; fast advances two.
  3. If fast hits 1, the number is happy — stop.
  4. If slow == fast before that, both landed in the unhappy cycle.
  5. Same answers as the set method, but with constant extra memory.

Edge Cases & Pitfalls

Check these before calling the solution done.

1

Already happy

1 is happy immediately. Do not force an extra step.

Cycle

Must detect loops

Without a set or Floyd, unhappy inputs loop forever.

0 / negatives

Out of scope

Happy numbers are defined for positive integers. Reject the rest.

Squares

Not digit sum

You square each digit. Plain digit sum is a different problem.

Time and Space Complexity

ProgramTimeExtra space
Visited HashSetO(k · log n)O(k)
FloydO(k · log n)O(1)

Each square-sum step costs O(digits). Values shrink quickly into a small range, so k (chain length until 1 or a cycle) stays small in practice.

Key Takeaways

  • Definition: keep summing digit squares; reach 1 → happy.
  • Stop safely: use a set or Floyd so unhappy inputs do not loop forever.
  • Floyd: slow moves once, fast moves twice; meet at 1 or a cycle.
  • Test set: 19 and 7 happy; 2 and 4 unhappy.

One line: sum digit squares until you reach 1 — or detect the unhappy cycle.

Frequently Asked Questions

Start with a positive integer n and repeatedly replace it with the sum of the squares of its digits. If the process reaches 1, n is happy.
Yes. It already equals 1, so no further work is needed.
It never reaches 1. Instead it enters the cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
Two pointers move at different speeds. If they meet at a value other than 1, you found a loop — with O(1) extra memory.
Yes. Store every value you have seen. If you see a repeat before 1, the number is unhappy. Clearer, but uses extra memory.
The usual definition uses positive integers. Reject nonpositive inputs (or treat them as not happy).

Next: Harshad Number

Check whether a number is divisible by the sum of its digits.

Harshad number 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.

11 people found this page helpful