Project Euler 92

Square digit chains

Problem 92

A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.

For example,

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

Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.

How many starting numbers below ten million will arrive at 89?


0.57s,重复组合数什么的。(F 的 120s 真的太彪悍了。)

import itertools
import time

def conquer():
    ans = 0
    DIGIT_LIMIT = 7
    ITER_STR = "0123456789"
    sum_square = lambda ss: sum( int( s ) ** 2 for s in str( ss ) )
    fact = lambda num: reduce( lambda x, y: x * y, xrange( 1, num + 1 ) )
    combinations = itertools.combinations_with_replacement( ITER_STR, DIGIT_LIMIT )
    
    def combinatorial_num( num ):
        res = fact( DIGIT_LIMIT )
        s = str( num )
        for ss in ITER_STR:
            count = s.count( ss )
            if count > 1: res /= fact( count )
        return res
    
    for c in combinations:
        num = int( "".join( c ) )
        if num == 0: continue
        while num != 89 and num != 1:
            num = sum_square( num )
        if num == 89:
            ans += combinatorial_num( c )

    print ans

begin = time.time()
conquer()
end = time.time()
print end - begin


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值