a=input("Enter a number")
for i in range(0,len(a)):
print(a[i])
Finding sum of the factorials of digit and comparing
Using the factorial function created ( my_factorial() ), the Sum of the factorials of digits of the number can be calculated.
my_sum=my_sum+my_factorial(int(a[i]))
Above line is kept inside the for loop. So on each step of the loop one digit of the number is used ( from left to right ).
This value of my_sum can be compared with the input number by using if condition check and accordingly message can be displayed saying about the strong number.
Full code to check input number is strong number or not
def my_factorial(n):
b=1
for i in range(1,n+1):
b=b*i
return b
a=input("Ener a number : ")
my_sum=0
for i in range(0,len(a)):
my_sum=my_sum+my_factorial(int(a[i]))
print("Sum of factorial of digits : ",my_sum)
if int(a)==my_sum:
print('This is a strong number : ', a)
else:
print('This is not a strong number', a)
Listing all strong numbers over a range
We can modify the above code to check all the numbers over a range and display the strong numbers.
def my_factorial(n):
b=1
for i in range(1,n+1):
b=b*i
return b
for a in range(10,100000): # change this range
my_sum=0
a1=str(a)
for i in range(0,len(a1)):
my_sum=my_sum+my_factorial(int(a1[i]))
if a==my_sum:
print('This is a strong number : ', a)
Output
This is a strong number : 145
This is a strong number : 40585
Note : By default all inputs are string data type(even if you enter a number.)
You can check the data type of the inputs by using type() len() : returns the length of ( chars ) of a string.