简体   繁体   English

java.math.BigInteger的问题

[英]Problems with java.math.BigInteger

I have the following code at the head of a method: 我在方法的开头有以下代码:

BigInteger foo = BigInteger.valueOf(0);
BigInteger triNum = BigInteger.valueOf(0);

//set min value to 1*2*3*4*5*...*199*200.
BigInteger min = BigInteger.ONE;
BigInteger temp = BigInteger.ZERO;
for(int i=1; i<=200; i++)
{
    temp = BigInteger.valueOf(i);
    min = min.multiply(temp);
}
System.out.println(min);

while(triNum.compareTo(min) <= 0)
{
    foo.add(BigInteger.ONE);
    triNum = triNum.add(foo);
    System.out.println("triNum: "+triNum);
}

This is supposed to load a min to a value (1 * 2 * 3 * ... * 199 * 200), and then set triNum to the first *triangle number** with a value greater than min. 这应该将min加载为值(1 * 2 * 3 * ... * 199 * 200),然后将triNum设置为第一个* triangle number **,其值大于min。

Problem is, when I run the method, all I get is a terminal window with a list of "triNum: 0" ever scrolling down the screen... I don't see anything in my code (although it is completely possible I made some mistake, and I am somewhat unfamiliar with math.BigInteger), and this seems to point back to the BigInteger class. 问题是,当我运行该方法时,我得到的只是一个终端窗口,该终端窗口在屏幕上向下滚动时显示“ triNum:0”列表...我的代码中什么也看不到(尽管我完全有可能有些错误,而我对math.BigInteger有点不熟悉,这似乎可以追溯到BigInteger类。 Anyone see a bug in my code? 有人在我的代码中看到错误了吗?

.......................................................................................................................... ................................................... ................................................... ......................

*A triangle number is a number that can be reached by: 1+2+3+4+5+6+7+... *三角形数字是可以达到的数字:1 + 2 + 3 + 4 + 5 + 6 + 7 + ...

Look at 看着

foo.add(BigInteger.ONE);

Does this update foo ? 这会更新foo吗? Or does it create an object that's equal to foo+ BigInteger.ONE which is not used again? 还是创建一个等于foo+ BigInteger.ONE且不再使用的对象?

foo is always 0. You need to change this line: foo始终为0。您需要更改以下行:

foo.add(BigInteger.ONE);

to this: 对此:

foo = foo.add(BigInteger.ONE);
 foo.add(BigInteger.ONE);

由于BigIntegers是不可变的,因此需要再次将结果分配给foo:

 foo = foo.add(BigInteger.ONE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM