Happy Numbers
Check happy numbers by repeating digit-square sums in Python. Students track visited states and stop either at one or when a repeated state proves a cycle.
1def sum_square_digits(n):2 total = 03 while n > 0:4 digit = n % 105 total += digit * digit6 n //= 107 return total89def is_happy(n):10 seen = set()11 while n != 1 and n not in seen:12 seen.add(n)13 n = sum_square_digits(n)14 return n == 11516# Test17num = int(input("Enter a number: "))18if is_happy(num):19 print("Happy number")20else:21 print("Not a happy number")
Output
Enter a number: 19 Happy number
In this one
- Iterate a number transform
- Detect a repeated state
- Distinguish cycles from success
How it works
- 1
Start a fresh seen set.
- 2
Record n and replace it with its digit-square sum.
- 3
Stop on one or a previously seen state.
Edge cases
Why store seen values?
Why store seen values?
To stop when the process repeats instead of reaching one.
Is zero happy here?
Is zero happy here?
No. It repeats zero without reaching one.
What's going on
sum_square_digits replaces a positive integer by the total of its squared digits. is_happy repeats that transformation.
seen records each state before the next step. Reaching one succeeds; revisiting any earlier state prevents an infinite cycle and fails. For nineteen, the path reaches one. Zero stays in a cycle at zero, while negative input falls to zero under this helper's loop.
Why store seen values? To stop when the process repeats instead of reaching one.
Is zero happy here? No. It repeats zero without reaching one.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What signals success?
Pick an answer to check it.
Question 2
Why store seen values?
Pick an answer to check it.
Questions people ask
Why store seen values?
To stop when the process repeats instead of reaching one.
Is zero happy here?
No. It repeats zero without reaching one.
What signals success?
n == 1.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum