0
0
PythonProgramBeginner · 2 min read

Python Program to Find Happy Number

A happy number in Python can be found by repeatedly replacing the number with the sum of the squares of its digits until it becomes 1 (happy) or loops endlessly (not happy); use def is_happy(n): with a loop and a set to track seen numbers.
📋

Examples

Input19
OutputTrue
Input2
OutputFalse
Input7
OutputTrue
🧠

How to Think About It

To find if a number is happy, keep replacing it by the sum of the squares of its digits. If this process reaches 1, the number is happy. If it starts repeating numbers, it means it will never reach 1 and is not happy.
📐

Algorithm

1
Start with the given number.
2
Create a set to remember numbers already seen.
3
Repeat: replace the number by the sum of the squares of its digits.
4
If the number becomes 1, return True (happy).
5
If the number repeats (seen before), return False (not happy).
💻

Code

python
def is_happy(n):
    seen = set()
    while n != 1 and n not in seen:
        seen.add(n)
        n = sum(int(d)**2 for d in str(n))
    return n == 1

print(is_happy(19))  # True
print(is_happy(2))   # False
print(is_happy(7))   # True
Output
True False True
🔍

Dry Run

Let's trace the number 19 through the code to see if it is happy.

1

Initial number

n = 19, seen = {}

2

Calculate sum of squares of digits

1^2 + 9^2 = 1 + 81 = 82

3

Update number and seen set

n = 82, seen = {19}

4

Repeat sum of squares

8^2 + 2^2 = 64 + 4 = 68

5

Update number and seen set

n = 68, seen = {19, 82}

6

Repeat sum of squares

6^2 + 8^2 = 36 + 64 = 100

7

Update number and seen set

n = 100, seen = {19, 82, 68}

8

Repeat sum of squares

1^2 + 0^2 + 0^2 = 1 + 0 + 0 = 1

9

Number is 1, happy number found

Return True

IterationCurrent NumberSum of SquaresSeen Numbers
11982{19}
28268{19, 82}
368100{19, 82, 68}
41001{19, 82, 68, 100}
💡

Why This Works

Step 1: Sum of squares of digits

We break the number into digits and calculate the sum of their squares using int(d)**2.

Step 2: Detect loops with a set

We keep track of numbers seen before in a set to detect if the process is stuck in a loop.

Step 3: Check for happiness

If the number becomes 1, it is happy; if it repeats, it is not.

🔄

Alternative Approaches

Recursive approach
python
def is_happy_recursive(n, seen=None):
    if seen is None:
        seen = set()
    if n == 1:
        return True
    if n in seen:
        return False
    seen.add(n)
    next_n = sum(int(d)**2 for d in str(n))
    return is_happy_recursive(next_n, seen)

print(is_happy_recursive(19))
Uses recursion instead of a loop; easier to read but may hit recursion limits for large inputs.
Floyd's cycle detection
python
def next_number(n):
    return sum(int(d)**2 for d in str(n))

def is_happy_floyd(n):
    slow = n
    fast = next_number(n)
    while fast != 1 and slow != fast:
        slow = next_number(slow)
        fast = next_number(next_number(fast))
    return fast == 1

print(is_happy_floyd(19))
Uses two pointers to detect cycles without extra space; more efficient in space.

Complexity: O(log n) time, O(log n) space

Time Complexity

Each iteration calculates the sum of squares of digits, which takes O(log n) time because the number of digits is proportional to log n. The loop runs until a cycle or 1 is found, which is bounded.

Space Complexity

We store seen numbers in a set, which can grow up to O(log n) in the worst case due to the number size reducing over iterations.

Which Approach is Fastest?

The Floyd's cycle detection method uses constant space and is faster in practice, while the set method is simpler and easier to understand.

ApproachTimeSpaceBest For
Set trackingO(log n)O(log n)Simplicity and clarity
RecursiveO(log n)O(log n)Readability but limited by recursion depth
Floyd's cycle detectionO(log n)O(1)Memory efficiency and speed
💡
Use a set to track seen numbers to avoid infinite loops when checking happy numbers.
⚠️
Not tracking seen numbers causes infinite loops for numbers that are not happy.