【发布时间】:2017-07-25 04:51:58
【问题描述】:
我有一些基本代码可以解决 Euler 项目中的一个问题,确切地说是 48 号。虽然它在技术上产生了答案,但我希望我的程序能够整齐地呈现答案,因此我想将最后 10 位数字打印到控制台并省略其他所有内容。
我看过一些帖子建议人们对原始数据类型使用模运算符,虽然我不知道为什么返回余数可以作为一种解决方案,但我还是尝试了它,但无济于事。
System.out.println(GrandTotal.mod(BigInteger.TEN));
导入 java.math.BigInteger;
public class eulerNo48 {
public static void main(String[] args)
{
/**
* Loop that calculates the each number from 1 to 1000 to the
* power of itself and sums the results.
*/
BigInteger sum = BigInteger.ZERO;
BigInteger tempVar = BigInteger.ONE;
BigInteger GrandTotal = BigInteger.ZERO;
for (int i = 1; i <= 1000; i++) {
sum = tempVar.pow(i); // Calculates the value of tempVar(1 - 1000) to its respective power (i).
tempVar = tempVar.add(BigInteger.ONE); // Increments temVar for each iteration of the loop.
GrandTotal = GrandTotal.add(sum); // Adds sum to the grand total.
}
System.out.println(GrandTotal);
}
}
我们不胜感激。
【问题讨论】:
标签: biginteger