(當N非常大時)巧用Java函式BigInteger計算N階乘
阿新 • • 發佈:2019-02-20
資料型別 型別名 位長 取值範圍 預設值
布林型 boolean 1 true,false false
位元組型 byte 8 -128-127 0
字元型 char 16 ‘\u000’-\uffff ‘\u0000’
短整型 short 16 -32768-32767 0
整型 int 32 -2147483648,2147483647 0
長整型 long 64 -9.22E18,9.22E18 0
浮點型 float 32 1.4E-45-3.4028E+38 0.0
雙精度型 double 64 4.9E-324,1.7977E+308 0.0
這裡特別要提出出的兩種型別:
BigInteger 任意大的整數,原則上是,只要你的計算機的記憶體足夠大,可以有無限位的
BigInteger 任意大的實數,可以處理小數精度問題。
BigInteger中一些常見的函式:
A=BigInteger.ONE
B=BigInteger.TEN
C=BigInteger.ZERO
一些常見的數的賦初值。將int型的數賦值給BigInteger,BigInteger.valueOf(k);
基本的函式:
valueOf:賦初值
add:+ a.add(b);
subtract:-
multiply:*
divide:/
remainder:this % val
divideAndRemainder:a[0]=this / val; a[1]=this % val
pow:a.pow(b)=a^b
gcd,abs:公約數,絕對值
negate:取負數
signum:符號函式
mod:a.mod(b)=a%b;
shiftLeft:左移,this << n ,this*2^n;
shiftRight:右移,this >> n,this/2^n;
and:等同於c++的&&,且;
or:||,或;
xor:異或,BigInteger xor(BigInteger val),this^val
not:!,非;
bitLength:返回該數的最小二進位制補碼錶示的位的個數,即 不包括 符號位 (ceil(log2(this <0 ? -this : this + 1)))。對正數來說,這等價於普通二進位制表示的位的個數。
bitCount:返回該數的二進位制補碼錶示中不包括符號位在內的位的個數。該方法在 BigIntegers 之上實現位向量風格的集合時很有用。
isProbablePrime:如果該 BigInteger 可能是素數,則返回 true ;如果它很明確是一個合數,則返回 false 。 引數 certainty 是對呼叫者願意忍受的不確定性的度量:如果該數是素數的概率超過了 1 - 1/2*certainty方法,則該方法返回 true 。執行時間正比於引數確定性的值。
compareTo:根據該數值是小於、等於、或大於 val 返回 -1、0 或 1;
equals:判斷兩數是否相等,也可以用compareTo來代替;
min,max:取兩個數的較小、大者;
intValue,longValue,floatValue,doublue:把該數轉換為該型別的數的值。
1,BigInteger屬於java.math.BigInteger,因此在每次使用前都要import 這個類。偶開始就忘記import了,於是總提示找不到提示符。
2,其構造方法有很多,但現在偶用到的有: BigInteger(String val)
將 BigInteger 的十進位制字串表示形式轉換為 BigInteger。
BigInteger(String val, int radix)
將指定基數的 BigInteger 的字串表示形式轉換為 BigInteger。
如要將int型的2轉換為BigInteger型,要寫為BigInteger two=new BigInteger("2"); //注意2雙引號不能省略
3,BigInteger類模擬了所有的int型數學操作,如add()==“+”,divide()==“-”等,但注意其內容進行數學運算時不能直接使用數學運算子進行運算,必須使用其內部方法。而且其運算元也必須為BigInteger型。
如:two.add(2)就是一種錯誤的操作,因為2沒有變為BigInteger型。
4,當要把計算結果輸出時應該使用.toString方法將其轉換為10進位制的字串,詳細說明如下:
String toString()
返回此 BigInteger 的十進位制字串表示形式。
輸出方法:System.out.print(two.toString());
5,另外說明三個個用到的函式。 BigInteger remainder(BigInteger val)
返回其值為 (this % val) 的 BigInteger。
BigInteger negate()
返回其值是 (-this) 的 BigInteger。
int compareTo(BigInteger val)
將此 BigInteger 與指定的 BigInteger 進行比較。
remainder用來求餘數。
negate將運算元變為相反數。
compare的詳解如下:
compareTo
public int compareTo(BigInteger val)將此 BigInteger 與指定的 BigInteger 進行比較。對於針對六個布林比較運算子 (<, ==, >, >=, !=, <=) 中的每一個運算子的各個方法,優先提供此方法。執行這些比較的建議語句是:(x.compareTo(y) <op> 0),其中 <op> 是六個比較運算子之一。
指定者:
介面 Comparable<BigInteger> 中的 compareTo
引數:
val - 將此 BigInteger 與之比較的 BigInteger。
返回: