本文主要是介绍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 timedef conquer():ans = 0DIGIT_LIMIT = 7ITER_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 resfor c in combinations:num = int( "".join( c ) )if num == 0: continuewhile num != 89 and num != 1:num = sum_square( num )if num == 89:ans += combinatorial_num( c )print ansbegin = time.time()
conquer()
end = time.time()
print end - begin
这篇关于Project Euler 92的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!