C# Unhappy Number Program

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

What Is an Unhappy Number?

Take a positive integer and repeatedly replace it with the sum of the squares of its digits. If the chain never reaches 1, the number is an unhappy number. It gets stuck in a loop that always passes through 4.

Remember
n is unhappy  ⇔  digit-square chain never reaches 1

Example: 2
  2² = 4
  4² = 16
  1² + 6² = 37
  3² + 7² = 58
  5² + 8² = 89
  8² + 9² = 145
  1² + 4² + 5² = 42
  4² + 2² = 20
  2² + 0² = 4   ← back to 4 (cycle)

The unhappy cycle:
  4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
nChain (short)Result
22 → 4 → 16 → … (cycle)Unhappy
44 → 16 → 37 → … → 4Unhappy
1already 1Happy (not unhappy)
1919 → 82 → 68 → 100 → 1Happy (not unhappy)

How to Check an Unhappy Number in C#

Four clear steps — then pick the quick stop-at-4 check or a visited set.

  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 4 (unhappy).
  4. Or store each value in a HashSet and stop when a value repeats before 1.
MethodIdeaExtra spaceBest for
Stop at 4Every unhappy chain passes through 4O(1)Short, simple interview answer
Visited setStop when a value repeatsO(k)No special-number trick needed

Pseudocode

Pseudocode
function SumOfSquares(n):
    total = 0
    while n > 0:
        d = n mod 10
        total = total + d * d
        n = n / 10
    return total

function IsUnhappy(n):
    if n <= 0:
        return false

    while n != 1 and n != 4:
        n = SumOfSquares(n)

    return n == 4

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Core steptotal += (n % 10) * (n % 10); n /= 10
Unhappy whenChain never reaches 1 and enters the 4-cycle
Happy whenChain reaches 1
Known cycle4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
Quick stopwhile (n != 1 && n != 4)
Classic unhappy2, 3, 4, 5, 6, 8, 9, 11
Classic happy1, 7, 10, 13, 19, 23

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 = 2
Chain: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
Verdict: UNHAPPY NUMBER

Worked Walkthrough — n = 2

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

Calculation
Step 1: 2²           = 4     ← stop: reached 4

The chain continues in the cycle:
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4

It never reaches 1 → 2 is unhappy

C# Programs

Start with the short stop-at-4 check. Then use a HashSet when you want to detect any repeat without relying on the special cycle.

Example 1 — Stop at 4

Keep applying the digit-square step until n is 1 (happy) or 4 (unhappy).

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 IsUnhappy(int n)
    {
        if (n <= 0)
        {
            return false;
        }

        while (n != 1 && n != 4)
        {
            n = SumOfSquares(n);
        }
        return n == 4;
    }

    static void Main()
    {
        int number = 2;
        if (IsUnhappy(number))
        {
            Console.WriteLine(number + " is an Unhappy Number.");
        }
        else
        {
            Console.WriteLine(number + " is not an Unhappy 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. Loop while n is neither 1 nor 4, replacing it with SumOfSquares(n).
  4. Every unhappy chain enters the cycle that contains 4, so reaching 4 means unhappy.
  5. Return n == 4. For 2, the first step gives 4 → unhappy.

Example 2 — Visited HashSet

Store every value you produce. A repeat before 1 means the chain is looping.

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 IsUnhappy(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()
    {
        Console.WriteLine(IsUnhappy(2) ? "2 is unhappy" : "2 is happy");
        Console.WriteLine(IsUnhappy(19) ? "19 is unhappy" : "19 is happy");
        Console.WriteLine(IsUnhappy(4) ? "4 is unhappy" : "4 is happy");
    }
}

How It Works

  1. Reuse the same SumOfSquares helper as the stop-at-4 version.
  2. While n is not 1 and has not been seen, add it to seen and replace it with SumOfSquares(n).
  3. If n becomes 1, the number is happy.
  4. If n reappears in seen, you hit a cycle — the number is unhappy.
  5. Return n != 1: still not 1 after the loop means unhappy.

Edge Cases & Pitfalls

Check these before calling the solution done.

1

Happy, not unhappy

1 is already happy, so it is never unhappy.

4

Unhappy right away

4 sits in the cycle itself, so the stop-at-4 loop returns true immediately.

Cycle

Must stop the loop

Looping only until n == 1 never ends for unhappy numbers. Stop at 4 or use a set.

0 / negatives

Out of scope

The definition uses positive integers. Reject the rest.

Time and Space Complexity

ProgramTimeExtra space
Stop at 4O(k · log n)O(1)
Visited HashSetO(k · log n)O(k)

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: the digit-square chain never reaches 1 — unhappy.
  • Quick check: loop until 1 or 4; ending at 4 means unhappy.
  • HashSet: a repeated value before 1 proves a cycle.
  • Test set: 2 and 4 unhappy; 1, 7, and 19 happy.

One line: sum digit squares; if you land on 4 instead of 1, the number is unhappy.

Frequently Asked Questions

A positive integer that never reaches 1 when you repeatedly replace it with the sum of the squares of its digits. It ends up looping in the cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
A number that does reach 1 under the same digit-square process. Every positive integer is either happy or unhappy.
Every unhappy number eventually lands in the cycle that contains 4. So if the process hits 4, you can stop and answer unhappy without storing visited values.
Yes. 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, and it never reaches 1.
No. 1 is already happy because it equals 1. Unhappy numbers never reach 1.
The definition uses positive integers. Reject n <= 0 before running the process.

Next: Harshad Number

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

Harshad number tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful