Write a Python program to find if a number is strong number or not

PythonServer Side ProgrammingProgramming

What is a Strong Number?

A Strong number is one that is equal to the sum of the factorial of its digits.

Example

145
Factorial of 1=1
Factorial of 4=24
Factorial of 5=120
Sum=1+24+120
   =145

Following program is to find if the input number is a strong number or not. Return ‘True’ if the number is a strong number, else return ‘False’.

  • We are using two functions isStrong() which determines whether the number is strong or not, second method is factorial() which returns the factorial of the passed digit.

  • The factorial() is called from inside isStrong() to get factorials of all the digits(n%10) and add it to the sum.

  • After factorial of all the digits are summed up, the sum is compared to the original number, if they are equal, true is returned, else false is returned.

  • Why are we copying n into num in isStrong() ? On iterating through the while loop, the value of n will change to zero.But we require the original value to be compared with the sum later on and hence, we need to copy value of n into some variable before it is changed.

  • The factorial() uses recursion to calculate the factorial of the digits.

Example

def factorial(d):
   if(d==1 or d==0):
      return 1
   return d*factorial(d-1)
def isStrong(n):
   num=n
   sm=0
   while(n>0):
      digit=n%10
      sm=sm+factorial(digit)
      n=n//10
   if(sm==num):
      return True
   else:
      return False
print("Input a number")
a=int(input())
print(isStrong(a))

Output

Input a number
145
True
raja
Published on 10-Mar-2021 14:18:25
Advertisements