0

我被要求在 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)

当我运行它时,什么都没有出现。我知道可能会有一个非常微不足道的错误,但是我花了一整天的时间寻找它,却一无所获。请帮忙。

4

1 回答 1

1

尽管您的代码在我的机器上只需要 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)
于 2019-02-01T19:49:33.623 回答