### Digit factorial chains题号：74 难度： 15 中英对照

The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:

1! + 4! + 5! = 1 + 24 + 120 = 145

Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist:

169 → 363601 → 1454 → 169
871 → 45361 → 871
872 → 45362 → 872

It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,

69 → 363600 → 1454 → 169 → 363601 (→ 1454)
78 → 45360 → 871 → 45361 (→ 871)
540 → 145 (→ 145)

Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.

How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?

### Code

/**
* Created by Tao on 2017/5/28.
*/
import java.util.*;

public  class p74 {
public static void main(String[] args) {
long start=System.nanoTime();
String result = run();
long end=System.nanoTime();
System.out.println(result);
System.out.println( (end-start)/1000000 + "ms" );
}
static public String run(){
final int LIMIT=1000000;
int count = 0;
// 对1000000内所有数字遍历,找到满足条件的所有数
for (int i = 0; i < LIMIT; i++) {
if (getChainLength(i) == 60)
count++;
}
return Integer.toString(count);
}

private static int getChainLength(int n) {
// 通过Hash Set 来存储所有的中间结果,出现重复时,返回已有不同中间结果数的个数
Set<Integer> seen = new HashSet<Integer>();
while (true) {
return seen.size();
n = factorialize(n);
}
}

// 0-9 的阶乘
private static int[] f = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};

// 对n,求各位数字阶乘之和
private static int factorialize(int n) {
int sum = 0;
// 对n 从低位到高位,依次求取该位的阶乘,求和
for (; n != 0; n /= 10)
sum += f[n % 10];
return sum;
}
}
402
1268ms