题目
一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
my_code:
import numpy as np
def factor(num):
a = []
for i in range(2,num):
if num % i ==0:
a.append(i)
a.append(1)
a = list(set(a))
if np.sum(a)== num:
return True
else:
return False
for i in range(2,1001):
if factor(i):
print('%i is a perfect number'%i)
输出:
> 6 is a perfect number
> 28 is a perfect number
> 496 is a perfect number
Reference code:
from sys import stdout
for j in range(2,1001):
k = []
n = -1
s = j
for i in range(1,j):
if j % i == 0:
n += 1
s -= i
k.append(i)
if s == 0:
print j
for i in range(n):
stdout.write(str(k[i]))
stdout.write(' ')
print k[n]
** 注意 **:sys.stdout.write()函数类似于print函数,两者之间的区别详见链接