Python program to print all happy numbers between 1 and 100

Created with Sketch.

Python Program to Print Happy Numbers Between 1 and 100

Introduction

In this blog post, we will explore and implement a Python program to print all Happy Numbers within the range of 1 to 100. Happy Numbers are a fascinating mathematical concept that involves a sequence of operations on the digits of a number. We will provide a step-by-step explanation of the Happy Number concept, outline the algorithm for identifying Happy Numbers, present the Python program, and showcase its output with examples.

Understanding Happy Numbers

Happy Numbers are numbers that, when the digits are squared and summed, eventually result in the number 1. The process involves repeatedly replacing a number by the sum of the squares of its digits. If this process leads to 1, the number is considered a Happy Number. If the process loops endlessly in a cycle other than 1, the number is not a Happy Number.

Algorithm to Print Happy Numbers Between 1 and 100

The algorithm for printing Happy Numbers between 1 and 100 can be outlined as follows:

  1. Iterate Through Numbers: Use a loop to iterate through each number in the specified range (1 to 100).
  2. Check for Happiness: For each number, implement the process of checking whether it is a Happy Number.
  3. Print Happy Numbers: If a number is found to be happy, print it.
  4. Output Result: Display the list of Happy Numbers within the given range.

Python Program Implementation

Now, let’s implement the algorithm in a Python program:

def is_happy_number(num):
    seen_numbers = set()

    while num != 1 and num not in seen_numbers:
        seen_numbers.add(num)
        num = sum(int(digit) ** 2 for digit in str(num))

    return num == 1

def print_happy_numbers():
    print("Happy numbers between 1 and 100:")

    for num in range(1, 101):
        if is_happy_number(num):
            print(num, end=" ")

# Example usage
print_happy_numbers()

Output:

The output of the program will be the list of Happy Numbers between 1 and 100.

Conclusion

This Python program effectively identifies and prints Happy Numbers within the specified range. The algorithm uses a set to keep track of seen numbers during the process. Understanding the concept of Happy Numbers provides insights into mathematical patterns and iterative processes. You can modify the range or experiment with different numbers to explore additional Happy Numbers. Happy coding!

Happy numbers between 1 and 100:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100

Leave a Reply

Your email address will not be published. Required fields are marked *