我一直在尝试解决Project Euler 中的问题 20 :
嗯!表示 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;
}