Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to print all Happy numbers between 1 and 100
A happy number is a number that eventually reaches 1 when replaced by the sum of the square of its digits repeatedly. For example, 7 is happy because 7² = 49, then 4² + 9² = 97, then 9² + 7² = 130, and so on until we reach 1.
Numbers that don't reach 1 will eventually cycle. The most common cycle includes 4, which is why we check for it as a stopping condition.
Algorithm
To find happy numbers between 1 and 100 ?
- For each number, repeatedly calculate the sum of squares of its digits
- If the result equals 1, it's a happy number
- If the result equals 4, it will cycle and is not happy
- Continue until we reach either 1 or 4
Example
def check_happy_num(my_num):
remaining = sum_val = 0
while(my_num > 0):
remaining = my_num % 10
sum_val = sum_val + (remaining * remaining)
my_num = my_num // 10
return sum_val
print("The list of happy numbers between 1 and 100 are:")
for i in range(1, 101):
my_result = i
while(my_result != 1 and my_result != 4):
my_result = check_happy_num(my_result)
if(my_result == 1):
print(i)
Output
The list of happy numbers between 1 and 100 are: 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100
How It Works
Let's trace through how 7 becomes a happy number ?
def trace_happy_number(num):
print(f"Tracing {num}:")
original = num
while num != 1 and num != 4:
digits = [int(d) for d in str(num)]
squares = [d**2 for d in digits]
num = sum(squares)
print(f" {' + '.join(map(str, squares))} = {num}")
if num == 1:
print(f" {original} is a happy number!")
else:
print(f" {original} is not happy (reached cycle)")
trace_happy_number(7)
print()
trace_happy_number(2)
Tracing 7: 49 = 49 97 = 97 130 = 130 10 = 10 1 = 1 7 is a happy number! Tracing 2: 4 = 4 2 is not happy (reached cycle)
Alternative Implementation
Here's a more concise version using string manipulation ?
def is_happy(n):
while n != 1 and n != 4:
n = sum(int(digit)**2 for digit in str(n))
return n == 1
happy_numbers = [i for i in range(1, 101) if is_happy(i)]
print("Happy numbers from 1 to 100:")
print(happy_numbers)
Happy numbers from 1 to 100: [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]
Conclusion
Happy numbers are identified by repeatedly summing the squares of their digits until reaching 1 (happy) or 4 (unhappy cycle). There are 20 happy numbers between 1 and 100, with the algorithm efficiently detecting them using modular arithmetic or string manipulation.
