[Project Euler] Problem 21

來源:互聯網
上載者:User

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

 

這道題用python來表達本來就是一句話的。但是在寫過程發現執行時間太長了,還是改了下。:

   1:  def sumpd(n):
   2:      """Return the d(n)"""
   3:      return sum([x for x in range(1, n) if n % x == 0])
   4:  orgamilist = [x for x in range(1, 10001) if sumpd(sumpd(x)) == x]
   5:  amilist = [x for x in orgamilist if sumpd(x) != x]
   6:  print sum(amilist)

 

這裡面弟4行和第5行代碼千萬不要合并。第五行和第六行代碼合并起來寫是沒問題的。

 

總結出來的教訓就是:

列表裡面千萬不要用太複雜的綜合運算式,會嚴重降低效率,還是建議列表裡面的條件盡量簡單。

 

這個程式雖然簡單,但是演算法還是值得商榷,上面的代碼運行大概需要10秒的時間,這個時間還是不太滿意的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.