- Path
- 82 -> 68 -> 100 -> 1
Check Happy Number in Python
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
% 10and// 10to 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.
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
- Cycle
- 4 -> 16 -> ...
Takeaway: either 1 is reached, or a repeat appears.
Live preview
Positive integers only in JavaScript safe range.
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
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 == 1Single value: 19
Floyd cycle detection for one value with positive-input guard.
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.
Happy numbers in [1, 50]
Checks each number independently and prints only happy ones.
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
🔄 Input / output examples
Change number in Example 1 or scan range in Example 2.
| n | Happy? |
|---|---|
1 | Yes |
7 | Yes |
2 | No |
19 | Yes |
Edge cases and pitfalls
Keep input positive and ensure digit function is pure/deterministic.
Immediate happy
It stays at 1.
Not positive
Treat as invalid for standard definition.
Input validation
Reject negatives instead of guessing behavior.
Decimal assumption
This page uses base-10 digits only.
⏱️ Time and space complexity
| Method | Time (per check) | Extra space |
|---|---|---|
| Floyd (this page) | O(μ + λ) digit-sum steps | O(1) |
| Visited set | same step class | O(k) |
Scan [1, N] | O(N) checks | O(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.
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.
8 people found this page helpful
