Python Program to Check Strong Number

1. Introduction

In this tutorial, we will learn how to write a Python program to check if a number is a Strong number.

A strong number, also known as a factorial number, is a number where the sum of the factorials of its digits is equal to the number itself. For example, 145 is a strong number because 1! + 4! + 5! = 145.

2. Program Steps

1. Accept or define a number to check for being a strong number.

2. Split the number into its individual digits.

3. Calculate the factorial of each digit.

4. Sum the factorials of all the digits.

5. Compare the sum with the original number to determine if it is a strong number.

6. Print the result.

3. Code Program

# Function to calculate the factorial of a number
def factorial(num):
    if num == 0 or num == 1:
        return 1
    else:
        return num * factorial(num - 1)

# Function to check if a number is a strong number
def is_strong_number(number):
    # Convert the number to string for easy digit extraction
    str_number = str(number)
    # Sum the factorials of the digits
    sum_factorials = sum(factorial(int(digit)) for digit in str_number)
    # Compare the sum with the original number
    return sum_factorials == number

# Number to be checked
num_to_check = 145
# Check if the number is a strong number and print the result
if is_strong_number(num_to_check):
    print(f"{num_to_check} is a strong number.")
else:
    print(f"{num_to_check} is not a strong number.")

Output:

145 is a strong number.

Explanation:

1. factorial is a recursive function that computes the factorial of num, which is the product of all positive integers up to num.

2. is_strong_number is a function that checks if number is a strong number.

3. It turns number into a string str_number to iterate over its digits.

4. sum_factorials is calculated using a generator expression, which sums the factorial of each digit converted back to an integer.

5. The function compares sum_factorials to number and returns True if they are equal.

6. num_to_check is set to 145, and is_strong_number is called to determine if it is a strong number.

7. A message is printed to state whether 145 is a strong number, based on the sum of the factorials of its digits being equal to the number itself.

Comments