2015-11-02 139 views
-1

所以我給了一個問題,告訴我要製作一個整數階乘達到30的表格。本書特別告訴我要使用BigInteger對象。 (使用BigInteger big = BigInteger.valueOf(x))然而,這樣做非常棘手,給了我一堆我不知道如何解決的錯誤。什麼時候使用BigInteger對象而不是簡單地使用double?

例如

public static BigInteger factorial(int a){ 
     if(a == 0){ 
      return BigInteger.valueOf(1); 
     } 
     else{ 
      return BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1)));// this will keep giving me an error message that I need to change the value type to "long" and back and forth to BIgInteger. I've tried many different variations including where I use BigInteger.valueOf(..) to every values. 
     } 

    } 

你知道使用的BigInteger對象以正確的方式?

你什麼時候會使用BigInteger而不是double?取而代之的

BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1))) 

import java.math.BigInteger; 
     public class BigInt { 

      public static double factorial(int a){ 
       if(a == 0){ 
        return 1; 
       } 
       else{ 
        return a* factorial(a-1); 
       } 

      } 
      public static void table(int a){ 
       for(int i =0; i<=a; i++){ 
        System.out.println(i + ", " + factorial(i)); 

        } 
       } 

      public static void main(String[] args) { 
      table(30); 
      } 

     } 

回答

1

當您使用BigInteger時,不能使用*等操作符。您必須使用BigInteger類的方法:

return factorial(a-1).multiply(a); 

之所以使用BigInteger代替double是精度。 double精度有限,所以不能準確表示大整數。

編輯:你應該實際使用

return BigInteger.valueOf(a).multiply(factorial(a-1)); 

因爲BigInteger multiply(long v)是包私有。

+0

...並且因爲它清楚地表明你代表*整數*而非任意有理數是有用的...... –

+0

我在[Javadoc](https)中看不到'multiply(int)'或'multiply(long)' ://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#multiply(java.math.BigInteger中))。 –

1

嘗試

factorial(a - 1).multiply(BigInteger.valueOf(a)) 

您正在嘗試使用*操作繁殖的intBigInteger;這在Java中是不允許的,因爲不支持運算符重載。

至於爲什麼要使用BigInteger而不是doubledouble在開始舍入前僅支持有限數量的有效數字。使用BigInteger可讓您擁有任意大的數字。

+0

哦,我明白了。它不是原始類型,所以*不起作用。 – user87902

+0

那麼你什麼時候會使用BigInteger而不是double? – user87902

+0

@ user87902已更新 –

0

當使用大整數進行數值計算時,例如使用BigInteger時,也需要使用BigInteger。加密目的。用於浮動或雙打的四捨五入將使得應用這些密碼方法的理論成爲不可能。

相關問題