Python Program to Find Happy Number
def is_happy(n): with a loop and a set to track seen numbers.Examples
How to Think About It
Algorithm
Code
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
Dry Run
Let's trace the number 19 through the code to see if it is happy.
Initial number
n = 19, seen = {}
Calculate sum of squares of digits
1^2 + 9^2 = 1 + 81 = 82
Update number and seen set
n = 82, seen = {19}
Repeat sum of squares
8^2 + 2^2 = 64 + 4 = 68
Update number and seen set
n = 68, seen = {19, 82}
Repeat sum of squares
6^2 + 8^2 = 36 + 64 = 100
Update number and seen set
n = 100, seen = {19, 82, 68}
Repeat sum of squares
1^2 + 0^2 + 0^2 = 1 + 0 + 0 = 1
Number is 1, happy number found
Return True
| Iteration | Current Number | Sum of Squares | Seen Numbers |
|---|---|---|---|
| 1 | 19 | 82 | {19} |
| 2 | 82 | 68 | {19, 82} |
| 3 | 68 | 100 | {19, 82, 68} |
| 4 | 100 | 1 | {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
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))
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))
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set tracking | O(log n) | O(log n) | Simplicity and clarity |
| Recursive | O(log n) | O(log n) | Readability but limited by recursion depth |
| Floyd's cycle detection | O(log n) | O(1) | Memory efficiency and speed |