您的位置:首页 > 其它

欧拉工程第30题:Digit fifth powers

2015-05-05 21:35 375 查看
题目链接:https://projecteuler.net/problem=30

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 1^4 + 6^4 + 3^4 + 4^4

8208 = 8^4 + 2^4 + 0^4 + 8^4

9474 = 9^4 + 4^4 + 7^4 + 4^4

As 1 = 14 is not a sum it is not included.

The sum of these numbers is 1634 + 8208 + 9474 = 19316.

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

对于这样的形式,计算这个数等于各位数字5次方的所有数之和。

暴力破解

问题是如何设置开始条件和结束条件。

1.根据问题本身来看,这样的数一定很少,题目给的例子是4位数,让计算的数据应该不会很大,我设置的上线是999999,输入答案就对了,发现最大的数才是:194979.

2.在题解中发现,每位数最大的是9,9^5=59049,如果最满足最大条件的数有9位,9*9^5=531441,远小于123456789

9*9^5=531441

8*9^5=472392

7*9^5=413343

6*9^5=354294

OK,最大数不会超过354294,当然其实还差的很远,上界改成354294试试。

上界999999运行时间:1秒731毫秒

上界354294运行时间:0秒570毫秒

时间还是有很大差别的,但是我们把满足条件的数输出了,下面测试不输出的情况。与上面对应的两个时间差不多,应该是输出数据比较少,对整体时间影响比较小。

package projecteuler21to30;

import java.util.Date;
class level30{
void solve(){
int sum=0;
for(int i=99;i<354294;i++){//354294
int[] Locat=getLocation(i);
if(i==getpow4(Locat)){
sum+=i;
//              System.out.println(i+","+getpow4(Locat));
}

}
System.out.println(sum);
}
int getpow4(int[] locat){
int pow4=0;
for(int i=0;i<locat.length;i++){
pow4=pow4+(int) Math.pow(locat[i], 5);
}
return pow4;
}
int[] getLocation(int num){
int[] Locat=new int[6];
Locat[0]=num%10;
Locat[1]=(num/10)%10;
Locat[2]=(num/100)%10;
Locat[3]=(num/1000)%10;
Locat[4]=(num/10000)%10;
Locat[5]=(num/100000)%10;//or num/10000
return Locat;
}
}
public class Problem30 {
public static void main(String[] args){
Date beginTime=new Date();
new level30().solve(); //443839
Date endTime=new Date();
long Time = endTime.getTime()-beginTime.getTime();
System.out.println("Time:"+Time/1000+"秒"+Time%1000+"毫秒");
}
}


在题解中整理过来一个Python代码

def prob30(x):
s=0
for i in range(99,999999):
t=0
for a in str(i):
t+=int(a)**x
if t==i:
s+=t
return s

import time

t0=time.time()
ans=prob30(5)
t1=time.time()

usetime=t1-t0

print("ans: " + str(ans) + " in " + str(round(usetime, 5)) + " seconds")


ans: 443839 in 6.107 seconds


时间有点小长
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: