Skip to Main Content
Blog

Print all Happy Numbers in Python

Print all Happy Numbers in Python

Enter lower bound: 1
Enter upper bound: 99
1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97,
def squared_digits_sum(num: int, radix: int = 10) -> int:
    """
    Finds the squared digits' sum of a number in a given radix.

    Args:
    num (int): The input number.
    radix (int): The base of the number system (default is 10).

    Returns:
    int: The sum of the squared digits.
    """

    sum_of_squares = 0
    while num != 0:
        # Extract the last digit
        unit = num % radix
        # Add the square of the digit to the sum
        sum_of_squares += unit * unit
        # Remove the last digit from the number
        num //= radix
    return sum_of_squares


def is_happy(num: int) -> bool:
    """
    Checks if a number is a Happy number or not.

    Args:
    num (int): The input number.

    Returns:
    bool: True if the number is Happy, False otherwise.
    """

    radix = 10
    # Initialize a set to keep track of visited numbers
    visited = set()
    while True:
        # Calculate the sum of the squared digits
        sum_of_squares = squared_digits_sum(num)
        # If the sum is less than the radix, check if it's a cycle
        if sum_of_squares < radix:
            # If the sum is already visited, it's not a Happy number
            if sum_of_squares in visited:
                return False
            # Mark the sum as visited
            visited.add(sum_of_squares)
        # If the sum is 1, it's a Happy number
        if sum_of_squares == 1:
            return True
        # Update the number for the next iteration
        num = sum_of_squares


def main():
    # Get the lower and upper limits from the user
    lower_limit = int(input("Enter lower limit: "))
    upper_limit = int(input("Enter upper limit: "))

    # Find and print Happy numbers within the given range
    happy_numbers = [n for n in range(lower_limit, upper_limit + 1) if is_happy(n)]
    print(*happy_numbers, sep=", ")


if __name__ == "__main__":
    main()