java中的大整數計算

版權聲明:本文爲博主原創文章,允許轉載,不過請標明出處。 https://blog.csdn.net/zyh2525246/article/details/79574225

給2個整數,求和。很簡單。
那麼給出a=1234567898765432123456789,
b=123456789987654321123456789,求和,也不難。
將a逆序然後轉化爲一個數組,將b做同樣的操作。
對同下標的數進行相加,如果結果小於10,則將數放到較長的數組的改下標處,若果結果大於等於10,則進位(在下一個下標處加1),然後可能得到一個新的數組,將數組逆序輸出則可以得到結果。

但是,這樣寫起來不免有些繁瑣。

而用到BigInteger,無疑會變得很簡單。

BigInteger不是基本數據類型之一,是Java裏的一個類,它有點像像String,然而它的初始化方式卻沒有String那麼方便可以直接賦值,而是跟其他自定義的類一樣,要調用它的構造器進行初始化。這個類的取值範圍原則上是沒有上限的,取決於你的計算機的內存。

首先,先介紹他的構造方法:

  • BigInteger(byte[] val) :
    將包含 BigInteger 的二進制補碼錶示形式的 byte 數組轉換爲 BigInteger。
  • BigInteger(int signum, byte[] magnitude) :
    將 BigInteger 的符號-數量表示形式轉換爲 BigInteger。
  • BigInteger(int bitLength, int certainty, Random rnd) :
    構造一個隨機生成的正 BigInteger,它可能是一個具有指定 bitLength 的素數。
  • BigInteger(int numBits, Random rnd) :
    構造一個隨機生成的 BigInteger,它是在 0 到 (2numBits - 1)(包括)範圍內均勻分佈的值。
  • BigInteger(String val) :
    將 BigInteger 的十進制字符串表示形式轉換爲 BigInteger。
  • BigInteger(String val, int radix) :
    將指定基數的 BigInteger 的字符串表示形式轉換爲 BigInteger。

然後說一些常用的方法:
BigInteger add(BigInteger val):加
BigInteger subtract(BigInteger val):減
BigInteger multiply(BigInteger val):乘
BigInteger divide(BigInteger val):除
BigInteger pow(int ex) 次方
BigInteger abs() 絕對值
int intValue() 返回大整數的整型值
long longValue() 返回大整數的long型值
double doubleValue() 返回大整數的double類型的值
float floatValue() 返回大整數的float類型的值
String toString() 返回此 BigInteger 的十進制字符串表示形式。
String toString(int radix) 返回此 BigInteger 的給定基數的字符串表示形式。
BigInteger max(BigInteger val) 返回此 BigInteger 和 val 的最大值。
BigInteger min(BigInteger val) 返回此 BigInteger 和 val 的最小值。
BigInteger shiftLeft(int n) 將當前大整數左移n位後返回
BigInteger shiftRight(int n) 將當前大整數右移n位後返回

還有更多的方法請自行查找API……

那麼對於上面的問題,我們可以這樣做:

//這裏用到的構造方法是這個--BigInteger(String val) :
BigInteger base1 = new BigInteger("1234567898765432123456789");
BigInteger base2 = new BigInteger("123456789987654321123456789");
//add裏面的參數是BigInteger型,很容易因爲大意直接寫成字符串("1")
BigInteger total = base1.add(base2);

System.out.println(total);

這裏寫圖片描述

很簡單的3行代碼,就能完成大整數相加的操作。

再來說幾個簡單的例子:
求2的0次方+2的1次方+2的2次方+……+2的63次方

BigInteger total=new BigInteger("0"); // 當前總數
BigInteger base=new BigInteger("2"); // 基數
for(int i=0;i<64;i++){
    total=total.add(base.pow(i));
}

這裏寫圖片描述

求50!(50的階乘)

BigInteger base = new BigInteger("1");
BigInteger index = new BigInteger("1");
BigInteger total = new BigInteger("1");

for (int i = 1; i <= 50; i++) {
    total = total.multiply(index);
    index = index.add(base);
}

System.out.println(total);

這裏寫圖片描述

希望大家有所收穫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章