Given a range between two numbers M and O you have to print the strong numbers between the range M and O.
Strong number is defined as a number whose sum of factorial of each digit is equal to the number itself.
for example let's consider a number 40585
The number 40585 contains digits are
4
0
5
8
5
If we try to get the factorial of N numbers then it will be something like as shown below
4! = 24
0! = 1
5! = 120
8! = 40320
5! = 120
The sum of the factorial is evaluates to
24 + 1 + 120 + 40320 + 120 = 40585
The sum of the factorial is equal to the number itself. So 40585 is a strong number.
Write a Python Function to Print Nth Strong Numbers Between M And O
Let's import the required library. We require the math.factorial module to get the factorial of each and every individual digit of a number.
import math
Define a function that is start and end as an input value, the input values are range between M and O. Let's use the for loop to iterate from the start to end while we iterate, copy the contents of the number to temp and set the total to 0. total is used to store the sum of factorials of a number.
Using modulus addition and division (MAD), Use a while loop until temp value is not equals to zero, Get the last digit of a temp of performing modulus by 10, find factorial of a last digit and add to the total. then trim the last digit of temp value by true division by 10.
def strong(start, end):
for number in range(start, end + 1):
temp = number
total = 0
while temp != 0:
last_digit = temp % 10
total = total + math.factorial(last_digit)
temp = temp // 10
if total == number:
print(f"{number} is a Strong Number")
Using the if statement Check if total is equals to the number if so print the number as a strong number
Take two variables M and O and ask a user to enter the starting and ending range then convert this M and O to integers.
Call the function that we have defined above, by providing the two integer values m and o
m = int(input("Enter Value of M : "))
o = int(input("Enter Value of O : "))
strong(m, o)
Final program
========================
import math
def strong(start, end):
for number in range(start, end + 1):
temp = number
total = 0
while temp != 0:
last_digit = temp % 10
total = total + math.factorial(last_digit)
temp = temp // 10
if total == number:
print(f"{number} is a Strong Number")
m = int(input("Enter Value of M : "))
o = int(input("Enter Value of O : "))
strong(m, o)
Output
==================
Enter Value of M : 1
Enter Value of O : 10000000
1 is a Strong Number
2 is a Strong Number
145 is a Strong Number
40585 is a Strong Number
Conclusion
=================
Try to run the program by yourself by providing the random starting and ending range and note down the strong numbers.
0 Comments