我被要求在6之后找出三个连续的完美数字(即因子(包括1,不包括自身)之和为自身的数字)。以下是我的尝试:
# Find three consecutive perfect numbers after 6
def f(x):
"Find the sum of all factors."
factors = []
for i in range (1,x-1):
if x%i == 0:
factors.append (i)
else:
pass
return sum(factors)
counts = 0
perfect_numbers = []
x = 6
while counts <= 2:
x += 1
if x == f(x):
perfect_numbers.append (x)
counts += 1
else:
pass
print(perfect_numbers)当我运行它时,什么也没有显示出来。我知道可能会有一个非常小的错误,但我花了一整天的时间寻找它,但什么也没有找到。请帮帮忙。
发布于 2019-02-02 03:49:34
虽然你的代码在我的机器上只需要3秒就能计算出想要的结果,但我们可以通过改进下面这行代码将时间减半:
for i in range (1,x-1):在x之后的下一个最高因子是x / 2,因为2是1之后的下一个最小因子。这让我们可以将上面的代码重写为:
for i in range(1, x // 2 + 1):此外,如果您以后想在另一个程序中重用此代码,则使用range(1, x - 1)会导致f(2)不正确。针对上述问题和一些样式问题对代码进行了修改:
# Find three consecutive perfect numbers after 6
def f(x):
"Find the sum of all factors."
factors = []
for i in range(1, x // 2 + 1):
if x % i == 0:
factors.append(i)
return sum(factors)
count = 0
number = 6
perfect_numbers = []
while count < 3:
number += 1
if number == f(number):
perfect_numbers.append(number)
count += 1
print(perfect_numbers)https://stackoverflow.com/questions/54442226
复制相似问题