Project Euler 21
题目
Amicable numbers
Let be defined as the sum
of proper divisors of (numbers
less than which divide evenly
into ).
If and , where , then and are an amicable pair and each of and are called amicable numbers.
For example, the proper divisors of are , , , , , , , , , and ; therefore . The proper divisors of
are , , , and ; so .
Evaluate the sum of all the amicable numbers under .
因数和定理
如果一个正整数 分解后成为:
那么 的因数的和为: 更一般的,因数的 次幂的和为
计算因数和的函数将会封装在 tools
中并且以 divisor_sigma(n,k=None)
的方式调用。
解决方案
可以直接通过因数和定理,先将所有 以下的数进行分解,然后计算出真因数的值。
最后直接判断两对数是否满足亲和数的条件。
计算 中的所有因数和也可以通过欧拉筛加速计算。
代码
1 2 3 4 5 6 7 8 9 10 11 from tools import divisors_sigmaN = 10000 d = [0 for _ in range (N)] for i in range (1 , N): d[i] = divisors_sigma(i)-i ans = 0 for i in range (1 , N): if N > d[i] > i == d[d[i]]: ans += i + d[i] print (ans)