[英]How to find three consecutive perfect numbers?
我被要求在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)
當我運行它時,沒有任何顯示。 我知道可能有一個非常瑣碎的錯誤,但是我花了一整天時間尋找它,卻一無所獲。 請幫忙。
盡管您的代碼在我的計算機上只需要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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.