A strong number (also known as a factorial number) is a number that is equal to the sum of the factorials of its digits. For example, 145 is a strong number because (1! + 4! + 5! = 1 + 24 + 120 = 145).
Here's a Python function to check if a given number is a strong number:
import math
def is_strong_number(num):
"""
Check if a number is a strong number.
Args:
num (int): The number to check.
Returns:
bool: True if the number is a strong number, False otherwise.
"""
original_num = num
sum_of_factorials = 0
while num > 0:
digit = num % 10
sum_of_factorials += math.factorial(digit)
num //= 10
return sum_of_factorials == original_num
# Example usage:
print(is_strong_number(145)) # Output: True
print(is_strong_number(1)) # Output: True
print(is_strong_number(10)) # Output: False
Explanation:
- Import the
math module: This module provides the factorial function, which calculates the factorial of a number.
- Initialize variables:
original_num stores the original number to compare later.
sum_of_factorials accumulates the sum of the factorials of the digits.
- Extract digits and calculate factorials:
- Use a
while loop to extract each digit from the number.
- Calculate the factorial of the digit and add it to
sum_of_factorials.
- Remove the last digit from the number using integer division.
- Compare the sum of factorials with the original number:
- If they are equal, the number is a strong number.
- Otherwise, it is not.
Example Usage:
is_strong_number(145) returns True because (1! + 4! + 5! = 1 + 24 + 120 = 145).
is_strong_number(1) returns True because (1! = 1).
is_strong_number(10) returns False because (1! + 0! = 1 + 1 = 2 \neq 10).
This function efficiently checks if a number is a strong number by leveraging the math.factorial function and simple digit extraction.