【问题标题】:How to find three consecutive perfect numbers?如何找到三个连续的完美数?
【发布时间】:2019-02-02 03:49:33
【问题描述】:

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

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

【问题讨论】:

  • 这看起来是学习使用调试器的绝佳机会。
  • 我运行了你的代码,几秒钟后它给出了这个:[28, 496, 8128]
  • 我真的不知道该说什么,执行代码只是给了我接下来的3个完美数字
  • 代码正在运行并提供输出
  • 那么看起来你的问题与你如何运行代码有关。你能描述一下你是怎么做的吗?

标签: python perfect-numbers


【解决方案1】:

虽然您的代码在我的机器上只需要 3 秒来计算所需的结果,但我们可以通过改进这一行将时间减半:

for i in range (1,x-1):

x 本身之后的第二大因数是x / 2,因为21 之后的第二小除数。这让我们将上面的内容重写为:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多