Check Happy Number in Python

Beginner
⏱️ 9 min read
📚 Updated: May 2026
🎯 2 Code Examples
Floyd cycle

What you’ll learn

  • The happy-number iteration using sum of squared digits.
  • Floyd tortoise-hare cycle detection in O(1) memory.
  • Single check and range listing with a live preview.

Overview

Each number maps to another via digit-square sum. Sooner or later you either hit 1 (happy) or loop in a non-1 cycle (unhappy).

Two programs

Check one value and print happy numbers in [1, 50].

Live preview

Try any positive safe integer instantly.

Rigor

Positive-only definition and known unhappy cycle behavior.

Prerequisites

Digit extraction, loops, and Python functions.

  • Use % 10 and // 10 to process digits.
  • Know while loops and return values.

What is a happy number?

If repeated sum-of-square-of-digits reaches 1, the number is happy.

Example: 19 -> 82 -> 68 -> 100 -> 1.

Happyreaches 1
Unhappyrepeats cycle
Fixed point1 -> 1

Digit map

Define f(n) as sum of squared decimal digits of n. Happy numbers are values whose repeated f application reaches 1.

f(19)

1^2 + 9^2 = 82, then 8^2 + 2^2 = 68, then 100, then 1.

Intuition

19Happy
Path
82 -> 68 -> 100 -> 1
2Unhappy
Cycle
4 -> 16 -> ...

Takeaway: either 1 is reached, or a repeat appears.

Live preview

Positive integers only in JavaScript safe range.

Try 1, 7, 2, or 23.

Live result
Press “Check happy”.

Algorithm

Goal: decide if repeated digit-square sum reaches 1.

Build digit-square function

Extract each digit, square it, and accumulate.

Run Floyd pointers

slow = f(slow), fast = f(f(fast)). Meeting at 1 means happy.

📜 Pseudocode

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
1

Single value: 19

Floyd cycle detection for one value with 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.")

Explanation

The two pointers eventually meet. If they meet at 1, the number is happy.

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()

Explanation

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

Alternatives

Visited set: easy to understand but uses extra memory.

Known unhappy cycle: return false if sequence hits any cycle member.

Interview: explain why Floyd works on functional graphs.

❓ FAQ

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.

🔄 Input / output examples

Change number in Example 1 or scan range in Example 2.

nHappy?
1Yes
7Yes
2No
19Yes

Edge cases and pitfalls

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

n = 1

Immediate happy

It stays at 1.

n = 0

Not positive

Treat as invalid for standard definition.

Negative

Input validation

Reject negatives instead of guessing behavior.

Base

Decimal assumption

This page uses base-10 digits only.

⏱️ 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 tail length before cycle, λ is cycle length.

Summary

  • Happy: eventually reaches 1.
  • Detection: Floyd uses two-speed pointers, no hash set needed.
  • Watch-outs: validate positive input and remember unhappy cycle.
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.

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.

8 people found this page helpful