簡體   English   中英

如何優化我的代碼以打印友好的數字?

[英]How can I optimize my code to print amicable numbers?

我已經嘗試了以下代碼,當我設置 lower = 0 和 upper = 10000 時需要很長時間

def sumPdivisors(n):
  '''This function returns the sum of proper divisors of a number'''
  lst = []
  for i in range(1,n//2+1):
    if n%i == 0:
      lst.append(i)
  return(sum(lst))

lower = int(input("Enter the lower value of range: "))
upper = int(input("Enter the upper value of range: "))

lst = []

for i in range(lower, upper+1):
    if i == 0:
      continue
    else:
      for j in range(i, upper):
        if i!=j and sumPdivisors(i) == j and sumPdivisors(j) == i:
          lst.append((i,j))
          break

print(lst)

您可以在這里做兩件事。

記憶

這個網站[link]上的其他地方已經有一個很好的解釋,但這里是它與您的問題的相關性:

  • sumPdivisors在代碼片段底部的 for 循環中被非常頻繁地調用。 對於非常大的輸入n ,運行需要很長時間。

  • 使用相同的輸入n多次調用sumPdivisors

  • 您可以通過以某種方式保存在不同輸入上調用sumPdivisors的結果來加快速度,例如當您使用相應的 integer 調用sumPdivisors時,將整數映射到結果 output 的字典中。 這就是記憶化的一種。 您正在預先計算sumPdivisors的可能輸出並將它們存儲起來以備后用。 閱讀鏈接以獲得更深入的解釋。

不要將 sumPdivisors 中的數字添加到列表中

您可以在迭代時添加這些數字,而不是將它們附加到列表中,然后將它們相加。 此更改不會像在您的代碼中添加 memoization 那樣產生很大的影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM