Project Euler 241

Project Euler 241

题目

Perfection Quotients

For a positive integer n, let σ(n) be the sum of all divisors of n. For example, σ(6)=1+2+3+6=12.

A perfect number, as you probably know, is a number with σ(n)=2n.

Let us define the perfection quotient of a positive integer as p(n)=σ(n)n.

Find the sum of all positive integers n1018 for which p(n) has the form k+12, where k is an integer.

解决方案

可以将 σ(n)n=k+12 改写成:

(2k+1)n2σ(n)=1

对于一个质数 q,有 p(qk)=qk+11q11qk.

给定一个数 ab=2k+12,不停除上一些形如 p(qiki) 的值(其中 qi 是质数),那么这个数将会逐渐减少。如果恰好能减少到 1,那么就找到了一个答案 iqiki. 如果在除的过程中发现这个数小于 1 了,那么就返回。

对于质数 qi 的寻找方式:为了尽快消去分母 b,考虑对 b 进行分解质因数,那么假设找到 b 的分解中最小的一项为 re。那么就对 ab 尝试除 p(re),p(re+1),p(re+2), 往下继续进行搜索。

关于 k 的枚举,该页面给出了 p(n)(n>3) 的上限:

σ(n)n<eγloglogn+0.6483loglogn

其中 γ 为欧拉常数,值约为 0.5772156649. 因此,只需要保证 2k+12 在这个范围内即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from tools import gcd, factorization
from itertools import count
from math import exp, log

N = 10 ** 18
ans = 0
K = int((exp(0.57721566490153286) * log(log(N)) + 0.6483 / log(log(N)))*2)


def dfs(n: int, fz: int, fm: int):
if n * fz > N or gcd(n, fm) != 1 or fz < fm:
return
if fm == 1:
if fz == 1:
global ans
ans += n
return
p = factorization(fm)[0][0]
e = 1
while fm % p ** (e + 1) == 0:
e += 1
for i in count(e, 1):
nw = n * p ** i
if nw > N:
break
new_fz = fz * p ** i
new_fm = fm * (p ** (i + 1) - 1) // (p - 1)
g = gcd(new_fz, new_fm)
dfs(nw, new_fz // g, new_fm // g)


for i in range(3, K+1, 2):
dfs(1, i, 2)
print(ans)

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
Ujimatsu Chiya 微信 微信
Ujimatsu Chiya 支付宝 支付宝