求数字 100 中各个数字的总和! (我的 while 循环不会停止)
我一直在尝试解决欧拉项目中的问题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;
}
I've been trying to solve Problem 20 in Project Euler:
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!
This is what I came up with so far. I already got the correct answer (which was 648) with this code, but I got a bit OC, because my code is an infinite loop. After the result became 0 inside the while loop, it just wouldn't stop. Can anybody help me fix this?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是问题所在:
result
是一个BigInteger
,它永远不会等于Integer
。尝试使用This is the problem:
result
is aBigInteger
, which will never be equal to anInteger
. Try using另一种可能性是使用 while (fact.compareTo(BigInteger.ZERO) > 0)。
我建议您在可能的情况下使用 BigInteger.ZERO、BigInteger.ONE 和 BigInteger.TEN。
示例:
需要 4 毫秒。
可以使用以下观察来改进它:
5*k * 2*j
可以被10
整除。Another possibility is to use
while (fact.compareTo(BigInteger.ZERO) > 0)
.I recommend you to use
BigInteger.ZERO
,BigInteger.ONE
andBigInteger.TEN
where it is possible.Example:
It takes 4 ms.
It can be improved using the following observation:
5*k * 2*j
is divisible by10
.请将您的代码修改为:
Please modify your code to :
这是执行相同操作的另一种方法。在这种方法中,计算总和的复杂度是 O(1)。
计算下面的总和
Here is another way of doing the same.In this, the complexity to compute the sum is O(1).
computing the sum below