How can we generate Strong numbers in Python?

PythonProgrammingServer Side Programming

To print Strong Numbers, let's first look at the definition of it. It is a number that is the sum of factorials of its own digits. For example, 145 is a Strong number. First, create a function to calculate factorial:

def fact(num):
   def factorial(n):
   num = 1
   while n >= 1:
      num = num * n
      n = n - 1
   return num

You can print these numbers by running the following code:

def factorial(n):
   num = 1
   while n >= 1:
      num = num * n
      n = n - 1
   return num

def print_strong_nums(start, end):
   for i in range(start, end + 1):
      # Get the digits from the number in a list:
      digits = list(map(int, str(i)))
      total = 0
      for d in digits:
         total += factorial(d)
      if total == i:
         print(i)
print_strong_nums(1, 380)

This will give the output:

1
2
145
raja
Published on 20-Apr-2018 08:42:13
Advertisements