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秒的時間,這個時間還是不太滿意的。