gpt4 book ai didi

java - 求数字 100 中数字的总和! (我的 while 循环不会停止)

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:54:02 26 4
gpt4 key购买 nike

我一直在努力解决 Problem 20在欧拉计划中:

n! means n (n 1) ... 3 * 2 * 1 For example, 10! = 10 * 9 ... 3 * 2 * 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 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;
}

最佳答案

问题是:

while (!result.equals(0))

result 是一个 BigInteger,它永远不会等于 Integer。尝试使用

while (!result.equals(BigInteger.ZERO))

关于java - 求数字 100 中数字的总和! (我的 while 循环不会停止),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7770740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com