这是典型的在内向基环树结构,遍历所有数并缓存已经计算出的链长即可。结果是$402$。
import math
target=1000000
f=[math.factorial(i) for i in range(10)]
d=[0 for i in range(target)]
d[0]=2
s=0
for n in range(target):
terms=[]
m=n
while m not in terms and (m>=target or d[m]==0):
terms.append(m)
m=sum(f[int(i)] for i in str(m))
r=d[m] if m < target else 0
for i,j in enumerate(terms):
if j < target:
d[j]=len(terms)-i+r
s=s+(d[n]==60)
print s
|