您的位置:首页 > 大数据 > 人工智能

欧拉工程第74题:Digit factorial chains

2015-09-27 21:37 483 查看
题目链接: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");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: