- Chain
- ends at 1
Check Happy Number in C#
What you’ll learn
- What a happy number is: repeat “sum of squares of digits” until you hit
1or loop forever. - Two C# solutions: Floyd’s cycle detection (slow/fast pointers) and a beginner-friendly
HashSettracker. - 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 1–50.
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;,staticmethods,Console.WriteLine, string interpolation.- For Example 2:
using System.Collections.Generic;andHashSet<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.
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.
1919 → 82 → 68 → 100 → 1
Quick examples
- 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.
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
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 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.
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.
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.
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
🔄 Input / output examples
Change number in Main, or read from the console after validation.
| Input | Verdict | First few steps |
|---|---|---|
1 | Happy | 1 |
7 | Happy | 7 → 49 → 97 → 130 → 10 → 1 |
19 | Happy | 19 → 82 → 68 → 100 → 1 |
4 | Unhappy | 4 → 16 → 37 → 58 → … |
2 | Unhappy | Enters 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.
1
Already at the target — return happy immediately.
0
SumOfSquares(0) is 0, which loops on itself — not happy. Reject or document separately.
n < 0
Outside the usual definition — return false or throw with a clear message.
Unhappy numbers
Without cycle detection, a while (n != 1) loop never terminates. Always track repeats or use Floyd.
⏱️ Time and space complexity
| Approach | Time (single check) | Extra space |
|---|---|---|
| HashSet | O(log n) steps per digit peel × chain length | O(chain length) |
| Floyd (slow/fast) | Same order of steps | O(1) |
| Range 1–50 scan | O(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#:
HashSetfor clarity; Floyd’s slow/fast pointers for O(1) space. - Classic demo:
19is happy;4shows the unhappy loop.
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.
6 people found this page helpful
