题目92:考察具有有趣性质的平方数链。
通过将一个数各位的平方不断相加,直到遇到已经出现过的数字,可以形成一个数字链。
例如:
44 32
13
10
1
1
85 89
145
42
20
4
16
37
58
89
因此任何到达1或89的数字链都会陷入无限循环。令人惊奇的是,以任何数字开始,最终都会到达1或89。
以一千万以下的数字n开始,有多少个n会到达89?
# 有趣性质的平方数链。
def fn(n):
"""
通过将一个数各位的平方不断相加,直到遇到已经出现过的数字,可以形成一个数字链。
例如:
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
"""
n=int(n)
cache = [n,]
def each_mul(aa):
return sum([int(i)**2 for i in str(aa)])
while True:
n = each_mul(n)
cache.append(n)
if cache.count(n) > 1:
break
return cache
print ' -> '.join(map(lambda x:str(x),fn(44)))
print ' -> '.join(map(lambda x:str(x),fn(85)))
44 -> 32 -> 13 -> 10 -> 1 -> 1
85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89
1KW的计算量很大,考虑缓存
# 有趣性质的平方数链。
# 开始时缓存没有内容,计算出第一个出现重复的数字即停止,返回输入值a,最终计算值b
# cache_increase = {a:b}
# 下一轮计算过程中,每当出现值在cache_increase中,更新cache_increase.停止计算.
superCache = {}
def each_mul_sum(aa):
return sum([int(i)**2 for i in str(aa)])
def run_fn(m,n,checkNum):
"""升序循环"""
if m>n:m,n=n,m
count = 0 # 计数
for i in range(m,n+1):
tmp_cache = [i,]
tmp_n = i
while True:
tmp_n = each_mul_sum(tmp_n)
if tmp_n in superCache: # 命中缓存,更新较新值
if superCache[tmp_n] == checkNum:
count += 1
superCache[i] = superCache.pop(tmp_n)
break
# 没有命中
tmp_cache.append(tmp_n)
if tmp_cache.count(tmp_n) > 1:
# 计算出新值,更新缓存
superCache[i] = tmp_cache[-1]
if tmp_cache[-1] == checkNum:
count += 1
break
return count
import time
t1 = time.time()
print run_fn(1,10000000,89)
t2 = time.time()
print t2-t1
还能再优化么?