A strong number in Python is a number whose sum of factorials of its digits is equal to the original number. Here is a Python program that checks whether a given number is a strong number or not:
def factorial(n): """ Returns the factorial of a number n. """ if n == 0: return 1 else: return n * factorial(n-1) def is_strong(n): """ Returns True if a number n is a strong number, False otherwise. """ sum = 0 temp = n while temp > 0: digit = temp % 10 sum += factorial(digit) temp //= 10 return sum == n # Example usage print(is_strong(145)) # True print(is_strong(123)) # False
The factorial
function calculates the factorial of a number using recursion, and the is_strong
function checks whether a number is strong or not by iterating through its digits and calculating their factorials. The //
operator is used for integer division, which is needed to obtain the individual digits of a number.
Strong Number Using the for loop:
Certainly! Here’s a Python program that checks whether a given number is a strong number using a for
loop:
def factorial(n): """ Returns the factorial of a number n. """ if n == 0: return 1 else: return n * factorial(n-1) def is_strong(n): """ Returns True if a number n is a strong number, False otherwise. """ sum = 0 for digit in str(n): sum += factorial(int(digit)) return sum == n # Example usage print(is_strong(145)) # True print(is_strong(123)) # False
In this implementation, the for
loop iterates over each digit in the input number as a string, converts it to an integer, and calculates its factorial using the factorial
function. The sum of the factorials of all the digits is compared with the original number to determine whether it is a strong number or not.