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秒的时间,这个时间还是不太满意的。