如何在 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
广告