当前位置:首页 » Project Euler » 详细页

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?

Solution

本题直接采用暴力求解法遍历求解: - 为避免重复计算,先将0到9的阶乘硬编码到代码中(直接写到数组f中) $n \in \{0,1,2,\cdots, 9\}$时,直接通过数组下标 $f[n]$获得 $n !$ ; - 枚举遍历范围内所有数,判断其循环节是否为60,若是将计数器加一即可; - 判断时,不断进行题中的操作,直至搜索到某一结果已经在之前出现过(用一个HashSet保存所有结果),此时返回结果的个数(HashSet的大小)。 通过以上操作即可将1000000以内所有满足60循环的数统计出来。

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) {
            if (!seen.add(n))
                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