Happy Number in Python

A Happy Number is a positive integer where repeatedly replacing it with the sum of squares of its digits eventually leads to 1. If this process results in an endless cycle that never reaches 1, the number is not happy.

How Happy Numbers Work

Let's trace through the number 19 to see why it's happy ?

  • 1² + 9² = 1 + 81 = 82
  • 8² + 2² = 64 + 4 = 68
  • 6² + 8² = 36 + 64 = 100
  • 1² + 0² + 0² = 1 + 0 + 0 = 1

Since we reached 1, the number 19 is happy.

Algorithm Steps

  • Use a set to track visited numbers and detect cycles
  • Base case: if n equals 1, return True (happy number)
  • If n is already visited, return False (cycle detected)
  • Add n to the visited set
  • Calculate the sum of squares of digits
  • Recursively check with the new sum

Using Recursion with Cycle Detection

This approach uses recursion with a visited set to detect cycles ?

class Solution:
    def isHappy(self, n):
        return self.solve(n, set())
    
    def solve(self, n, visited):
        if n == 1:
            return True
        if n in visited:
            return False
        
        visited.add(n)
        
        # Calculate sum of squares of digits
        total = 0
        while n > 0:
            digit = n % 10
            total += digit ** 2
            n //= 10
        
        return self.solve(total, visited)

# Test the solution
solution = Solution()
result = solution.isHappy(19)
print("Is 19 happy:", result)

result2 = solution.isHappy(2)
print("Is 2 happy:", result2)
Is 19 happy: True
Is 2 happy: False

Using Iterative Approach

A simpler iterative approach without recursion ?

def is_happy_iterative(n):
    visited = set()
    
    while n != 1 and n not in visited:
        visited.add(n)
        total = 0
        
        # Calculate sum of squares of digits
        while n > 0:
            digit = n % 10
            total += digit ** 2
            n //= 10
        
        n = total
    
    return n == 1

# Test with different numbers
test_numbers = [19, 7, 2, 10]
for num in test_numbers:
    result = is_happy_iterative(num)
    print(f"{num} is {'happy' if result else 'not happy'}")
19 is happy
7 is happy
2 is not happy
10 is happy

Comparison

Approach Space Complexity Readability Best For
Recursive O(log n) + call stack Clear logic flow Educational purposes
Iterative O(log n) Simple loop Production code

Conclusion

Happy numbers can be detected by tracking visited numbers to avoid infinite cycles. The iterative approach is more efficient, while the recursive approach clearly shows the algorithm's logic.

Updated on: 2026-03-25T07:17:28+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements