Check Happy Number in Python

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Floyd cycle

What You’ll Learn

A happy number reaches 1 by repeatedly summing the squares of its digits. This tutorial covers the digit map, Floyd tortoise-hare detection, a visited-set alternative, a live preview, worked Python examples, edge cases, and complexity.

Definition

Reach 1

Repeat sum of squared digits until 1 or a cycle.

Classic 19

Happy

19 → 82 → 68 → 100 → 1.

Floyd

O(1) memory

Slow/fast pointers detect the cycle.

Unhappy Cycle

Starts at 4

4 → 16 → … → 20 → 4.

Live Preview

Try any n

Classify positive integers instantly.

O(μ+λ)

Floyd steps

Tail plus cycle length in digit-sum steps.

Introduction

A happy number is a positive integer that reaches 1 when you repeatedly replace it by the sum of the squares of its digits. Example: 19 → 82 → 68 → 100 → 1.

If the process never hits 1, it enters a fixed unhappy cycle (starting at 4). Floyd tortoise-hare detection finds that loop with O(1) extra memory.

Why it matters?

It combines digit peeling with cycle detection — a clean bridge from number warm-ups to linked-list Floyd problems.

Key Highlights

Digit Map f(n)

Sum of squared decimal digits.

Happy = Hit 1

1 is a fixed point: f(1) = 1.

Floyd Detects Loops

Slow/fast pointers meet in a cycle.

Positive Only

Reject 0 and negatives by definition.

In short: keep replacing n with the sum of squared digits; if you reach 1 it is happy, otherwise you loop.

📝 Problem & Approach

Given a positive integer n, decide whether repeated digit-square sums reach 1.

python
# 19 → 82 → 68 → 100 → 1   → happy
# 2  → 4  → 16 → ... cycle    → unhappy
# 1  → 1                       → happy

Inputs & Outputs

ItemTypeDescription
nintPositive integer (reject n < 1).
Return / printbool / textTrue if n is happy.

Minimal workflow

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

Method comparison

MethodIdeaNotes
Floydslow = f(slow), fast = f(f(fast))O(1) extra space — interview favorite
Visited setStop when value repeatsClearer; uses O(k) memory
Known cycleFalse if hit any of 4,16,…Fast shortcut after learning the cycle

⚡ Quick Reference

GoalPattern
Last digitn % 10
Drop digitn //= 10
Square sumtotal += digit * digit
Floyd stepslow = f(slow); fast = f(f(fast))
Happy classics1, 7, 19, 23
Unhappy classic2 (enters cycle at 4)

📋 Floyd vs Visited Set vs Known Cycle

Three ways to decide happy vs unhappy — pick by memory and clarity.

Floyd
slow / fast

O(1) space; interview default

Visited set
seen.add(n)

Easy to explain; uses extra memory

Known cycle
hit 4 → false

Shortcut once you know the cycle

Interview tip
Floyd first

Then mention the set alternative

Context

When This Problem Shows Up

Reach for happy-number checks when digit maps and cycles appear.

  1. Interview warm-ups

    Digit loops plus cycle detection in one prompt.

  2. Teaching Floyd

    Same tortoise-hare idea as linked-list cycle detection.

  3. Range listing tasks

    Print all happy numbers in 1…N for small N.

  4. After GCD

    Next classic number-theory style warm-up in this chain.

  5. Positive-only scope

    State that 0 / negatives are out of scope.

Key benefit: one short boolean check that forces clear thinking about functional graphs and cycles.

🔮 Live Preview

Positive integers only, within JavaScript safe range.

Try 1, 7, 2, or 23.

Live result
Press “Check happy”.

Examples Gallery

Three complete Python programs — Floyd single check, range 1–50, and visited-set style. Click View Output to reveal sample console results.

📚 Getting Started

Floyd tortoise-hare with O(1) extra memory.

Example 1 — Single Value: 19

Floyd cycle detection for one value with a positive-input guard.

python
def sum_of_squares(n: int) -> int:
    total = 0
    while n > 0:
        digit = n % 10
        total += digit * digit
        n //= 10
    return total


def is_happy(n: int) -> bool:
    slow = n
    fast = n
    while True:
        slow = sum_of_squares(slow)
        fast = sum_of_squares(sum_of_squares(fast))
        if slow == fast:
            break
    return slow == 1


number = 19
if number < 1:
    print("Use a positive integer.")
elif is_happy(number):
    print(f"{number} is a Happy Number.")
else:
    print(f"{number} is not a Happy Number.")

How It Works

The two pointers eventually meet. If they meet at 1, the number is happy; otherwise they met inside the unhappy cycle.

⚡ Range Output

Reuse the same helper to filter a beginner interval.

Example 2 — Happy Numbers in [1, 50]

Checks each number independently and prints only happy ones.

python
def sum_of_squares(num: int) -> int:
    total = 0
    while num > 0:
        digit = num % 10
        total += digit * digit
        num //= 10
    return total


def is_happy(num: int) -> bool:
    slow = num
    fast = num
    while True:
        slow = sum_of_squares(slow)
        fast = sum_of_squares(sum_of_squares(fast))
        if slow == fast:
            break
    return slow == 1


print("Happy numbers in the range 1 to 50:")
for i in range(1, 51):
    if is_happy(i):
        print(i, end=" ")
print()

How It Works

Each number uses the same happy check. Floyd keeps memory constant per check.

⚙️ Visited-Set Style

Easier to explain — trade O(1) space for clarity.

Example 3 — Track Seen Values

Stop when you hit 1 (happy) or see a repeated value (cycle).

python
def sum_of_squares(n: int) -> int:
    total = 0
    while n > 0:
        digit = n % 10
        total += digit * digit
        n //= 10
    return total


def is_happy_set(n: int) -> bool:
    if n < 1:
        return False
    seen = set()
    while n != 1 and n not in seen:
        seen.add(n)
        n = sum_of_squares(n)
    return n == 1


for value in (19, 2, 1, 7):
    label = "happy" if is_happy_set(value) else "unhappy"
    print(f"{value}: {label}")

How It Works

A set records every intermediate value. Repeating a value means you entered a cycle; hitting 1 means happy. Prefer Floyd when the interviewer asks for O(1) space.

🧠 How the Algorithm Decides

1

Digit-square map

Define f(n) as the sum of squared digits.

f(n)
2

Advance pointers

slow = f(slow), fast = f(f(fast)).

Floyd
3

Meet and decide

If meeting value is 1 → happy; else cycle.

Verdict
=

Happy or not

Reach 1 → yes; otherwise no.

🔎 Worked Walkthrough — n = 19

Trace the digit-square path for the classic happy example.

StepnDigit squaresNext
11912 + 9282
28282 + 2268
36862 + 82100
410012 + 0 + 01

Reached 1 → 19 is happy.

Use Cases

Where happy-number checks show up beyond the interview prompt.

1. Interview Warm-Ups

Digit peeling plus cycle detection.

Example: write is_happy(n).

2. Teaching Floyd

Same tortoise-hare idea as list cycles.

Example: slow/fast on f(n).

3. Range Filters

List happy numbers in a classroom interval.

Example: 1 to 50 list above.

4. Functional Graphs

Each n maps to exactly one next value.

Example: talk about μ and λ.

5. Digit Practice

% 10 / // 10 drills before harder digit problems.

Example: before Harshad next.

6. Unhappy Cycle Trivia

All unhappy positives share one 8-cycle.

Example: start at 4.

Pro Tip: say “happy means reach 1 under digit-square iteration” before coding Floyd.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Clear Rule

    One sentence: reach 1 via digit-square sums.

  2. 2. O(1) Detection

    Floyd needs no hash set for the cycle.

  3. 3. Famous Tests

    19 vs 2 makes verification quick.

  4. 4. Rich Follow-Ups

    Visited set, known cycle, and linked-list Floyd.

Pro Tip: lead with Floyd; offer a visited set if asked for the simplest version.

Usage Tips

Small habits that keep happy-number solutions interview-ready.

  1. 1. Extract f(n) First

    Write a clean sum-of-squares helper before Floyd.

  2. 2. Guard Positive n

    Reject n < 1 under the standard definition.

  3. 3. Spot-Check 19 and 2

    Happy and unhappy classics catch bugs fast.

  4. 4. Meet at 1 Means Happy

    Floyd meeting value is the decision signal.

  5. 5. Mention the Unhappy Cycle

    Shows you understand why Floyd terminates.

Pro Tip: 1 is happy because f(1) = 1 — say that when asked about the fixed point.

Common Pitfalls

Mistakes that commonly break happy-number solutions.

  1. 1. Summing Digits Without Squaring

    Using digit sum instead of digit-square sum.

    → Always square each digit.

  2. 2. Infinite Loop Without Cycle Check

    Iterating forever on unhappy numbers.

    → Use Floyd or a visited set.

  3. 3. Accepting Zero / Negatives

    Standard definition is positive integers only.

    → Reject n < 1.

  4. 4. Wrong Floyd Decision

    Returning true whenever pointers meet.

    → Check that the meeting value is 1.

  5. 5. Mutating n Inside Helpers Carelessly

    Reusing a destroyed working variable later.

    → Keep sum_of_squares pure on a local copy.

Edge Cases

Keep input positive and ensure the digit function is pure and deterministic.

n = 1

Immediate happy

It stays at 1.

n = 0

Not positive

Treat as invalid for the standard definition.

Negative

Input validation

Reject negatives instead of guessing behavior.

Base

Decimal assumption

This page uses base-10 digits only.

Unhappy

Cycle at 4

All unhappy positives enter the same 8-cycle.

Range

1 to 50

Expect 1 7 10 13 19 23 28 31 32 44 49.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Map. f(n) = sum of squared decimal digits; happy means some iterate equals 1.
  • Fixed point. f(1) = 1, so 1 is happy.
  • Unhappy cycle. 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
  • Bound. Digit-square sums shrink large n into a small range quickly.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Classify classics

  • 1, 7, 19 → happy
  • 2, 4 → unhappy

2. Match both styles

  • Floyd vs visited set
  • Assert identical booleans

3. Range 1 to 100

  • List all happy numbers
  • Compare with known lists

4. Print the path

  • Show 19 → 82 → … → 1
  • Stop at 1 or first repeat

Notes

  • Happy: eventually reaches 1.
  • Detection: Floyd uses two-speed pointers; no hash set needed.
  • Watch-outs: validate positive input and remember the unhappy cycle.
  • Per check: O(μ + λ) digit-sum steps with O(1) extra space (Floyd).

Quick Takeaway: sum squared digits repeatedly; if you reach 1 the number is happy, otherwise you loop.

⏱️ Time and Space Complexity

MethodTime (per check)Extra space
Floyd (this page)O(μ + λ) digit-sum stepsO(1)
Visited setsame step classO(k)
Scan [1, N]O(N) checksO(1) beyond each check

μ is the tail length before the cycle; λ is the cycle length. Each digit-sum step costs O(number of digits).

Wrap Up

🎉 Conclusion

Happy numbers reach 1 under repeated digit-square sums; unhappy ones enter a fixed cycle. Prefer Floyd for O(1) space, or a visited set for clarity — and always restrict to positive integers.

Practice the three examples above, then continue to Harshad numbers for another digit-sum divisibility check.

Meeting at 1 means happy; meeting elsewhere means the unhappy cycle.

💡 Best Practices

✅ Do

  • Write a pure sum-of-squares helper
  • Use Floyd for O(1) space
  • Test 1, 19, and 2
  • Reject nonpositive inputs
  • Mention the unhappy cycle

❌ Don’t

  • Forget to square digits
  • Return true on any pointer meeting
  • Loop forever without cycle detection
  • Accept 0 or negatives silently
  • Confuse digit sum with digit-square sum

Key Takeaways

Knowledge Unlocked

Five things to remember about happy numbers

Decide happiness the interview-friendly way.

5
Core concepts
f 02

Map

Σ d²

Digits
F 03

Floyd

O(1) space

Detect
4 04

Cycle

Unhappy 8-loop

Trivia
O 05

Cost

O(μ+λ)

Analysis

❓ Frequently Asked Questions

Starting from a positive integer n, repeatedly replace n by the sum of squares of its digits. If this process reaches 1, the number is happy.
Yes. It immediately maps to itself.
It detects loops with O(1) extra memory by moving two pointers at different speeds.
Happy numbers are defined for positive integers. Handle nonpositive inputs separately.
Standard definition uses positive integers only. Usually reject negatives at input.
Each digit-square step is O(log n) in decimal digits, and Floyd takes O(mu + lambda) such steps.
Yes. Track seen values and stop when you repeat or hit 1. It is clearer but uses extra memory.
All unhappy positives eventually enter 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

Did you Know? 🔊

If a positive integer is not happy, repeated digit-square sums enter the same unhappy cycle: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

Continue to Harshad Number

Learn how Harshad (Niven) numbers are divisible by the sum of their 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.

9 people found this page helpful