Happy Numbers
Check if number is happy number.
AdvancedPhase 6 - Category 1: Number LogicExample 8 of 10
happy-numbers.py
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
What's going on
Happy number: eventually reaches 1 by summing squares of digits.
Key Concepts:
Sum squares of digits repeatedly
Track seen numbers to detect cycle
Returns True if reaches 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