簡體   English   中英

java.math.BigInteger的問題

[英]Problems with java.math.BigInteger

我在方法的開頭有以下代碼:

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);
}

這應該將min加載為值(1 * 2 * 3 * ... * 199 * 200),然后將triNum設置為第一個* triangle number **,其值大於min。

問題是,當我運行該方法時,我得到的只是一個終端窗口,該終端窗口在屏幕上向下滾動時顯示“ triNum:0”列表...我的代碼中什么也看不到(盡管我完全有可能有些錯誤,而我對math.BigInteger有點不熟悉,這似乎可以追溯到BigInteger類。 有人在我的代碼中看到錯誤了嗎?

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

*三角形數字是可以達到的數字:1 + 2 + 3 + 4 + 5 + 6 + 7 + ...

看着

foo.add(BigInteger.ONE);

這會更新foo嗎? 還是創建一個等於foo+ BigInteger.ONE且不再使用的對象?

foo始終為0。您需要更改以下行:

foo.add(BigInteger.ONE);

對此:

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