Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python program to check whether a number is a Strong Number or not

Strong Number

Given a number ‘n’ we have to check whether the number given is Strong Number or not. Strong number is a number whose sum of all digits’ factorial is equal to the number ‘n’.

To check the number is Strong Number or not,We will extract every single digit,evaluate their factorial and add them all . If the given number is equal to the sum of the factorial ,then the given number is Strong number.

Example:

  • n=145
    • 145=1! + 4! + 5! (strong number)
  • n=124
    • 1! + 2! + 4! =27  (not a strong number)
finding a strong number using python

Implementation:

  • Take the input.
  • Extract each digit starting from the unit place and find its factorial.
  • Take the sum of all the factorial.
  • compare with the given number.

Python Code:

#Enter the number to check
print(‘Enter the number:’)
n=int(input())
#save the number in another variable 
temp=n 
sum=0
#Implementation
while(temp):
    r=temp%10 # r will have the value of the unit place digit
    temp=temp//10
    fac=1
    for i in range(1,r+1): #finding factorial
        fac=fac*i 
        
    sum+=fac #adding all the factorial
    
if(sum==n):
    print(‘Yes’, n ,‘is strong number’)
    
else:
    print(‘No’ , n, ‘is not a strong number’)
    
Output:

Enter the number:

145

Yes 145 is strong number

Optimal Solution:

#enter the number to check
print(‘Enter the number:’)
n=int(input())
#save the number in another variable 
temp=n 
sum=0
f=[0]*10
f[0]=1
f[1]=1
for i in range(2,10): #precomputing the factorial value from 0 to 9 and store in the array.
    f[i]=f[i-1]*i
#Implementation
while(temp):
    r=temp%10 #r will have the vale u of the unit digit
    temp=temp//10
    sum+=f[r] #adding all the factorial
    
if(sum==n):
    print(‘Yes’, n ,‘is strong number’)
    
else:
    print(‘No’ , n, ‘is not a strong number’)
Output:

Enter the number:

40585

Yes 40585 is strong number