2017-03-18 57 views
-2

我有以下代碼
BigInteger.pow()在最後2次迭代之前不起作用?

public static void main(String[] args) { 
    BigInteger iter = BigInteger.valueOf(140); 
    BigInteger y = BigInteger.valueOf(1114112); 
    BigInteger sum = BigInteger.valueOf(0); 
    while(iter.intValue() != 0) { 
     BigInteger z = BigInteger.valueOf((y.pow(iter.intValue())).longValue()); 
     sum = sum.add(z); 
     iter = iter.subtract(BigInteger.valueOf(1)); 
     System.out.println("Itereration: " + (140 - iter.longValue())); 
     System.out.println("Y: " + y.longValue()); 
     System.out.println("Z: " + z.longValue()); 
     System.out.println("Sum: " + sum.longValue()); 
    } 
} 

然而,輸出是這個(僅最後3次迭代)

Iteration: 137 
Y: 1114112 
Z: 0 
Sum: 0 
Iteration: 138 
Y: 1114112 
Z: 1382886560579452928 
Sum: 1382886560579452928 
Iteration: 139 
Y: 1114112 
Z: 1241245548544 
Sum: 1382887801825001472 
Iteration: 140 
Y: 1114112 
Z: 1114112 
Sum: 1382887801826115584 

迭代1-136的其餘部分是相同的迭代137

+2

邊注:爲什麼地球上是'iter'一個'BigInteger'? – 2017-03-18 13:04:18

+1

你的問題是什麼? –

+4

停止將您的BigInteger轉換成長整型和整數... –

回答

4

.longValue()呼叫在BigInteger這個值上做了完全錯誤的事情。如果您嘗試使用.longValueExact()來替代,您會發現它會拋出異常,因爲值超出long的範圍。但如果你不做不必要的.longValue()來電,代碼工作:

BigInteger iter = BigInteger.valueOf(140); 
BigInteger y = BigInteger.valueOf(1114112); 
BigInteger sum = BigInteger.valueOf(0); 
while(iter.intValue() != 0) { 
    BigInteger z = y.pow(iter.intValue(); 
    sum = sum.add(z); 
    iter = iter.subtract(BigInteger.valueOf(1)); 
    System.out.println("Itereration: " + (140 - iter.longValue())); 
    System.out.println("Y: " + y); 
    System.out.println("Z: " + z); 
    System.out.println("Sum: " + sum); 
} 

而作爲@RC。在註釋中曾建議,你可以做iter簡單int,從而簡化了代碼進一步:

int iter = 140; 
BigInteger y = BigInteger.valueOf(1114112); 
BigInteger sum = BigInteger.valueOf(0); 
while(iter != 0) { 
    BigInteger z = y.pow(iter); 
    sum = sum.add(z); 
    iter--; 
    System.out.println("Itereration: " + (140 - iter)); 
    System.out.println("Y: " + y); 
    System.out.println("Z: " + z); 
    System.out.println("Sum: " + sum); 
} 
+0

謝謝,不知道您可以用這種方式打印BigInteger的值。 –

相關問題