projecteuler.net 題目筆記 [92]

題目92:考察具備有趣性質的平方數鏈。

經過將一個數各位的平方不斷相加,直到遇到已經出現過的數字,能夠造成一個數字鏈。php

例如:
python

44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89緩存

所以任何到達1或89的數字鏈都會陷入無限循環。使人驚奇的是,以任何數字開始,最終都會到達1或89。app

以一千萬如下的數字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 -> 1spa

85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89code


1KW的計算量很大,考慮緩存orm

# 有趣性質的平方數鏈。
# 開始時緩存沒有內容,計算出第一個出現重複的數字即中止,返回輸入值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


還能再優化麼?get

相關文章
相關標籤/搜索