我一直在試圖解決Problem 20在項目歐拉:找到數字100中的數字總和! (我while循環不會停止)
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;
}
OMG的總和!我知道它必須沿着這些路線而行! > _ <非常感謝! <3 –