Check Happy Number in C#

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
Cycle detection

What you’ll learn

  • What a happy number is: repeat “sum of squares of digits” until you hit 1 or loop forever.
  • Two C# solutions: Floyd’s cycle detection (slow/fast pointers) and a beginner-friendly HashSet tracker.
  • How to list happy numbers in a range (1–50) and use a live preview that prints each step.

Overview

Happy numbers are a playful number-theory puzzle. You transform a number by squaring each digit and adding — then repeat. If the chain reaches 1, celebrate: it is happy. Otherwise the values eventually cycle, and the number is unhappy.

Two programs

Floyd for single checks and HashSet for scanning 150.

Live preview

Watch the digit-square chain for any positive integer you type.

Interview angle

Classic mix of digit math plus cycle detection — same idea as linked-list loops.

Prerequisites

Digit extraction with % 10 and / 10, loops, and basic collections.

  • using System;, static methods, Console.WriteLine, string interpolation.
  • For Example 2: using System.Collections.Generic; and HashSet<int>.

What is a happy number?

Take a positive integer. Replace it with the sum of the squares of its digits. Repeat until the value becomes 1 (happy) or you revisit a number you have already seen (unhappy cycle).

For 19: 1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1. So 19 is happy.

19 reaches 1
4 cycles
1 already happy

The digit-square step

Define f(n) as the sum of squares of decimal digits of n. A number is happy if repeated application of f eventually yields 1.

Trace for 19

19 → 82 → 68 → 100 → 1

Quick examples

19 Happy
Chain
ends at 1
4 Unhappy
Loop
16, 37, 58…

Happy numbers 1–50: 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49.

Live preview

Enter a positive integer. The widget prints each digit-square step until it reaches 1 or detects a cycle.

Try 19 (happy) or 4 (unhappy cycle).

Live result
Press “Trace steps” to run the digit-square chain.

Algorithm

Goal: return whether positive n is happy.

Define next step

Write GetNext(n) or SumOfSquares(n): peel digits with % 10, square each, add, divide n by 10.

Detect end state

HashSet: stop when n == 1 (happy) or n was seen before (unhappy). Floyd: advance slow one step and fast two steps until they meet.

Return verdict

Happy iff the meeting point (or final value) equals 1.

📜 Pseudocode

Pseudocode
function sumOfSquares(n):
    sum ← 0
    while n > 0:
        digit ← n mod 10
        sum ← sum + digit * digit
        n ← floor(n / 10)
    return sum

function isHappy(n):  // Floyd version
    slow ← n
    fast ← n
    repeat:
        slow ← sumOfSquares(slow)
        fast ← sumOfSquares(sumOfSquares(fast))
    until slow = fast
    return slow = 1
1

Single check with Floyd’s cycle detection

Checks whether 19 is happy using the slow/fast pointer technique — same pattern as detecting a loop in a linked list. No extra collection needed.

c#
using System;

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

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

        int slow = n;
        int fast = n;

        do
        {
            slow = SumOfSquares(slow);
            fast = SumOfSquares(SumOfSquares(fast));
        } while (slow != fast);

        return slow == 1;
    }

    static void Main()
    {
        int number = 19;

        if (IsHappyNumber(number))
        {
            Console.WriteLine($"{number} is a Happy Number.");
        }
        else
        {
            Console.WriteLine($"{number} is not a Happy Number.");
        }
    }
}

Explanation

SumOfSquares implements one transformation. slow moves one step per loop; fast moves two. When they meet, either you landed on 1 (happy) or inside the unhappy cycle (not 1).

fast = SumOfSquares(SumOfSquares(fast));

Two hops. This is what makes Floyd’s algorithm detect cycles in O(1) space.

2

Happy numbers from 1 to 50

Uses a HashSet<int> to remember visited values — easier to read for beginners. Scans the range and prints every happy number.

c#
using System;
using System.Collections.Generic;

class Program
{
    static int GetNextNumber(int num)
    {
        int result = 0;
        while (num > 0)
        {
            int digit = num % 10;
            result += digit * digit;
            num /= 10;
        }
        return result;
    }

    static bool IsHappy(int num)
    {
        HashSet<int> seen = new HashSet<int>();

        while (num != 1 && !seen.Contains(num))
        {
            seen.Add(num);
            num = GetNextNumber(num);
        }

        return num == 1;
    }

    static void Main()
    {
        Console.WriteLine("Happy numbers in the range 1 to 50:");

        for (int i = 1; i <= 50; i++)
        {
            if (IsHappy(i))
            {
                Console.Write($"{i} ");
            }
        }

        Console.WriteLine();
    }
}

Explanation

The while loop keeps transforming num until it hits 1 or revisits a value in seen. The outer for loop reuses IsHappy for every candidate in the range.

Beyond the basics

Floyd vs HashSet. Floyd uses constant extra space; HashSet is clearer and fine for interview-sized inputs.

Memoization. When scanning a range, cache results per starting value to avoid recomputing chains.

Interview: state the digit-square rule, walk through 19, then mention cycle detection — interviewers often ask for O(1) space after the HashSet version.

❓ FAQ

Start with a positive integer. Repeatedly replace it with the sum of the squares of its digits. If you eventually reach 1, the number is happy. If you loop forever without reaching 1, it is unhappy.
Yes. 19 → 82 → 68 → 100 → 1. The process ends at 1.
No. Starting from 4, the values cycle through 16, 37, 58, 89, 145, 42, 20, and back to 4 — never reaching 1.
Yes. The sum of squares of the digits of 1 is 1, so you are already at the target.
It detects loops using two pointers (slow and fast) without storing every visited value — O(1) extra space instead of a HashSet.
For beginners and range scans, a HashSet of seen values is straightforward: add each step until you hit 1 or see a repeat.
Happy numbers are defined for positive integers. Reject negatives in your program or document that the definition does not apply.

🔄 Input / output examples

Change number in Main, or read from the console after validation.

InputVerdictFirst few steps
1Happy1
7Happy7 → 49 → 97 → 130 → 10 → 1
19Happy19 → 82 → 68 → 100 → 1
4Unhappy4 → 16 → 37 → 58 → …
2UnhappyEnters the 4 cycle

Edge cases and pitfalls

Happy numbers are defined for positive integers. Handle corners explicitly so your program does not loop forever on bad input.

One

1

Already at the target — return happy immediately.

Zero

0

SumOfSquares(0) is 0, which loops on itself — not happy. Reject or document separately.

Negative

n < 0

Outside the usual definition — return false or throw with a clear message.

Cycle

Unhappy numbers

Without cycle detection, a while (n != 1) loop never terminates. Always track repeats or use Floyd.

⏱️ Time and space complexity

ApproachTime (single check)Extra space
HashSetO(log n) steps per digit peel × chain lengthO(chain length)
Floyd (slow/fast)Same order of stepsO(1)
Range 1–50 scanO(50 × cost per check)Depends on method

Each digit-square step shrinks large numbers quickly in practice, so chains stay short for typical interview inputs.

Summary

  • Rule: repeat sum of squares of digits until 1 (happy) or a cycle (unhappy).
  • C#: HashSet for clarity; Floyd’s slow/fast pointers for O(1) space.
  • Classic demo: 19 is happy; 4 shows the unhappy loop.
Did you know?

Every positive integer is either happy (the process reaches 1) or unhappy (it falls into a repeating cycle that never hits 1). The most famous unhappy loop starts at 4: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

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.

6 people found this page helpful