欧拉计划48题

/**
* Self powers
* Problem 48
*
* The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
*
* Find the last ten digits of the series,
* 1^1 + 2^2 + 3^3 + ... + 1000^1000.
*
* @author dcb
*
*/
计算1^1 + 2^2 + 3^3 + ... + 1000^1000
结果的后10位数字


分析:
这道题没什么难度,使用java语言要注意两个地方
1.int的范围,10位数使用int显然不够,要用long
2.计算的顺序,由于此题只需要计算后10位,因此计算乘方时,每乘一次对10^10进行取模操作,变可以保证不存在溢出情况

代码实现:
private static long solution(){
long result = 0l;
for (int i = 1; i <= 1000; i++){
result += selfPower(i);
}
return result % 10000000000l;
}

private static long selfPower(int num){
long result = 1l;
for (int i = 0; i < num; i++){
if (result == 0l){
return 0;
}
result *= num;
result = result % 10000000000l;
}
return result;
}


结果:9110846700







猜你喜欢

转载自535260620.iteye.com/blog/2283968