zoukankan      html  css  js  c++  java
  • 欧拉工程第74题:Digit factorial chains

    题目链接:https://projecteuler.net/problem=74

    数字145有一个著名的性质:其所有位上数字的阶乘和等于它本身。

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

    169不像145那么有名,但是169可以产生最长的能够连接回它自己的数字链。事实证明一共有三条这样的链:

    169 --> 363601 -->  1454 -->  169
    871 -->  45361 -->  871
    872 -->  45362 -->  872

    不难证明每一个数字最终都将陷入一个循环。例如:

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

    从69开始可以产生一条有5个不重复元素的链,但是以一百万以下的数开始,能够产生的最长的不重复链包含60个项。

    一共有多少条以一百万以下的数开始的链包含60个不重复项?

    import java.util.TreeSet;
    
    public class P74{
        void run(){
            int max_n=1000000;
            TreeSet<Long> ts = new TreeSet<Long>();
            int count=0;
            long num=0;
            int len=0;
            for(int i=69;i<max_n;i++){
                ts.clear();
                num = i;
                len = 0;
                while(ts.add(num)==true){
                    len++;
                    num=digitFact(num);
                    
                }
                if(len ==60)
                    count++;
            }
            System.out.println(count);
        }
    //    402
    //    13s9ms
        long digitFact(long num){
            long result = 0;
            while(num!=0){
                result += Factorial(num%10);
                num/=10;
            }
            return result;
        }
        long Factorial(long l){
            long fact = 1;
            for(int i =1;i<=l;i++)
                fact*=i;
            return fact;
        }
        
        public static void main(String[] args){
            long t0 = System.currentTimeMillis();
            new P74().run();
            long t1= System.currentTimeMillis();
            System.out.println((t1-t0)/1000+"s"+(t1-t0)%1000+"ms");
        }
    }
  • 相关阅读:
    poj 1743 Musical Theme 后缀数组
    poj 1743 Musical Theme 后缀数组
    cf 432D Prefixes and Suffixes kmp
    cf 432D Prefixes and Suffixes kmp
    hdu Data Structure? 线段树
    关于position和anchorPoint之间的关系
    ios POST 信息
    CALayers的代码示例
    CALayers详解
    ios中得sqlite使用基础
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4842805.html
Copyright © 2011-2022 走看看