我們如何在 Python 中生成強數?


若要列印強數,我們首先來看它的定義。它是一個數字,其本身數字階乘的總和。例如,145 是一個強數。首先,建立一個函式計算階乘

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

執行以下程式碼可以列印這些數字

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)

這將給出以下輸出

1
2
145

更新於: 17-6月-2020

172 次瀏覽

開啟您的 事業

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.