找出1~1000 内的所有完数,并按以下格式输出,6 its factors are 1,2,3。
时间: 2024-06-01 08:10:29 浏览: 56
编程找出1000之内的所有完数,并按下面格式输出其因子:6 its factors are 1,2,3
5星 · 资源好评率100%
完数是指一个正整数,它的所有因子(除了它本身)的和等于它本身。
以下是1~1000内的所有完数:
6 its factors are 1,2,3
28 its factors are 1,2,4,7,14
496 its factors are 1,2,4,8,16,31,62,124,248
8128 its factors are 1,2,4,8,16,32,64,127,254,508,1016,2032,4064
输出结果可以用以下Python代码实现:
def find_perfect_numbers():
perfect_numbers = []
for i in range(1, 1001):
factors = []
for j in range(1, i):
if i % j == 0:
factors.append(j)
if sum(factors) == i:
perfect_numbers.append(i)
return perfect_numbers
perfect_numbers = find_perfect_numbers()
for number in perfect_numbers:
factors = ",".join([str(i) for i in range(1, number) if number % i == 0])
print(f"{number} its factors are {factors}")
阅读全文