【发布时间】:2011-10-14 16:35:32
【问题描述】:
我一直在尝试解决 Project Euler 中的Problem 20:
n!表示 n (n 1) ... 3 * 2 * 1 例如,10! = 10 * 9 ... 3 * 2 * 1 = 3628800, 和数字 10 中的数字之和!是 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27。 求数字 100 中的数字之和!
这是我到目前为止想出的。我已经用这段代码得到了正确的答案(648),但我有点 OC,因为我的代码是一个无限循环。在 while 循环内结果变为 0 后,它就不会停止。谁能帮我解决这个问题?
public static BigInteger problem20(int max){
BigInteger sum = BigInteger.valueOf(0);
BigInteger result = BigInteger.valueOf(1);
BigInteger currentNum = BigInteger.valueOf(0);
for(long i = 1; i<=max; i++){
result = result.multiply(BigInteger.valueOf(i));
//System.out.println(result);
}
while (!result.equals(0)) {
sum = sum.add(result.mod(BigInteger.valueOf(10)));
result = result.divide(BigInteger.valueOf(10));
System.out.println(sum + " "+ result);
}
return sum;
}
【问题讨论】:
标签: java biginteger factorial