19):题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
#!/usr/bin/python
# -*- coding: UTF-8 -*- 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]
以上实例输出结果为:
6
1 2 3
28
1 2 4 7 14
496
1 2 4 8 16 31 62 124 248
#!/usr/bin/env python
# -*- coding: utf-8 -*- for i in range(1, 1001):
sum = 0
for j in range(1, i):
if i % j == 0:
sum += j
if sum == i:
print(i)
Python3 测试实例:
#!/usr/bin/python3 list2 = []
for x in range(1, 1001):
list1 = []
for i in range(1, int(x / 2) + 1):
if x % i == 0:
list1.append(i)
if x == sum(list1):
print(x)
print(list1)
list2.append(x)
print("共计有%d个完数"%(len(list2)))
#!/usr/bin/python
# -*- coding: UTF-8 -*-
__author__ = 'Arlene' def fun(num):
sum = 1 # 1要加上,所以默认赋值为1
for i in range(2, num): # 因子不包括本身,
if num % i == 0:
sum += i
if sum == num:
return num
result = []
for num in range(2, 1000):
test = fun(num)
if test: # 去掉空值
result.append(test)
print("完数有:", result)
#!/usr/bin/env python for i in range(1,1001):
s = 0
L = []
for x in range(1,int((i+3)/2)):
if i % x == 0:
s += x
L.append(x)
if i == s:
print(i)
print(L)
#!/usr/bin/env python
# -*- coding: utf-8 -*- l = []
def num(n):
for i in range(1,n + 1):
if n != i and n % i == 0:
l.append(i)
return l for i in range(1,1001):
sum = 0
l = []
m = num(i)
if m == []:
pass
else:
for j in m:
sum += j
if i == sum:
print i
#!/usr/bin/env python
# -*- coding: utf-8 -*- list1 = []
for j in range(2, 10001):
l = [] for i in range(1, j//2+1):
if j % i == 0:
l.append(i)
if j == sum(l):
list1.append(j)
print("{}={}".format("+".join(map(str, l)), j))
#!/usr/bin/python
# -*- coding: UTF-8 -*- Sn = []
for i in range(2,1001):
for j in range(1,i):
if i % j == 0:
Sn.append(j)
if i == reduce(lambda x,y : x + y,Sn):
print i,Sn
Sn = []
Python3 测试:
import functools for num in range(1,1001):
savenum=int(num)
list1 = []
for idx in range(1,int(num)):
if num % idx == 0:
list1.append(idx)
if functools.reduce(lambda x,y:x+y,list1,0) == savenum:
print(savenum,list1)
import numpy as np for m in range(1,1001):
n=[1]
for i in range(2,m):
if m % i == 0:
n.append(i)
if m == np.sum(n):
print m,n
有什么不懂得可以参考第十三个小例子。如果感觉不错的话,请多多点赞支持哦。。。
原文链接:https://blog.csdn.net/luyaran/article/details/80063230