Java大數(shù)字運算之BigInteger 原創(chuàng)
在 Java 中,有許多數(shù)字處理的類,比如 Integer 類。但是Integer 類有一定的局限性,下面我們就來看看比 Integer 類更厲害的一個,BigInteger類。
BigInteger類型的數(shù)字范圍較 Integer 類型的數(shù)字范圍要大得多。我們都知道 Integer 是 Int 的包裝類,int 的最大值為 231-1,如果要計算更大的數(shù)字,使用Integer 數(shù)據(jù)類型就無法實現(xiàn)了,所以 Java 中提供了BigInteger 類來處理更大的數(shù)字。 BigInteger 支持任意精度的整數(shù),也就是說在運算中 BigInteger 類型可以準(zhǔn)確地表示任何大小的整數(shù)值而不會丟失任何信息。
在 BigInteger 類中封裝了多種操作!除了基本的加減乘除操作之外,還提供了絕對值、相反數(shù)、最大公約數(shù)以及判斷是否為質(zhì)數(shù)等操作。
使用BigInteger 類,可以實例化一個BigInteger 對象,并自動調(diào)用相應(yīng)的構(gòu)造函數(shù)。BigInteger 類具有很多構(gòu)造函數(shù),但最直接的一種方式是參數(shù)以字符串形式代表要處理的數(shù)字。
語法如下:
public BigInteger(String val)
其中,val 是十進制字符串。
如果將 2 轉(zhuǎn)換為 BigInteger 類型,可以使用以下語句進行初始化操作:
BigInteger twoInstance = new BigInteger ("2");
一旦創(chuàng)建了對象實例,就可以調(diào)用 BigInteger 類中的一些方法進行運算操作,包括基本的數(shù)學(xué)運算和位運算以及一些取相反數(shù)、取絕對值等操作。下面是 BigInteger 類幾種常用的運算方法。
public BigInteger add(BigInteger val):做加法運算 public BigInteger subtract(BigInteger val):做減法運算 public BigInteger multiply(BigInteger val):做乘法運算 public BigInteger divide(BigInteger val):做除法運算 public BigInteger remainder(BigInteger val):做取余操作 public BigInteger pow(int exponet):進行取參數(shù)的 exponet 次方操作 public BigInteger negate():取相反數(shù) public BigInteger shiftLegt(int n):將數(shù)字左移 n 位,如果 n 為負數(shù),做右移操作 public BigInteger shiftRight(int n):將數(shù)字右移 n 位,如果 n 為負數(shù),做左移操作 public int compareTo(BigInteger val):做數(shù)字比較操作 public BigInteger max(BigInteger val):返回較大的數(shù)值
下面是一個實例。在項目中創(chuàng)建一個類,在類的主方法中創(chuàng)建 BigInteger 類的實例對象,調(diào)用該對象的各種方法實現(xiàn)大整數(shù)的加減乘除和其他運算,并輸出運行結(jié)果。
public static void main(String[] args) { BigInteger bigInstance = new BigInteger("4"); //實例化一個大數(shù)字 //取該大數(shù)字加2的操作 System.out.println("加法操作:"+ bigInstance.add(new BigInteger("2"))); //取該大數(shù)字減2的操作 System.out.println("減法操作:"+ bigInstance.subtract(new BigInteger("2"))); //取該大數(shù)字乘以2的操作 System.out.println("乘法操作:"+ bigInstance.multiply(new BigInteger("2"))); //取該大數(shù)字除以2的操作 System.out.println("除法操作:"+ bigInstance.divide(new BigInteger("2"))); //取該大數(shù)字除以3的商 System.out.println("取商:"+ bigInstance.divideAndRemainder(new BigInteger("3"))[0]); //取該大數(shù)字除以3的余數(shù) System.out.println("取余數(shù):"+ bigInstance.divideAndRemainder(new BigInteger("3"))[1]); //取該大數(shù)字的2次方 System.out.println("做2次方操作:"+ bigInstance.pow(2)); //取該大數(shù)字的相反數(shù) System.out.println("取相反數(shù)操作:"+ bigInstance.negate()); } }
以上就是關(guān)于 BigInteger 類的詳解和實例分析,喜歡的朋友請繼續(xù)關(guān)注腳本之家。
相關(guān)文章
淺談Java中OutOfMemoryError問題產(chǎn)生原因
本文主要介紹了淺談Java中OutOfMemoryError問題產(chǎn)生原因,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06Idea連接GitLab的過程以及創(chuàng)建在gitlab中創(chuàng)建用戶和群組方式
本文介紹了如何在IDEA中連接GitLab,首先需安裝GitLab插件并配置SSH免密登錄,接著,創(chuàng)建GitLab個人令牌并在Git中配置,文章還提到了如何在GitLab中創(chuàng)建用戶、群組及設(shè)置權(quán)限,如Owner、Maintainer、Developer等,并強調(diào)了群組名和人員名稱的命名規(guī)范2024-11-11