java中大數BigInger的使用


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

BigInteger構造器

這裏面最好用的應該是BigInger(String val)這個構造器吧,可以直接將十進制的字符串格式變成大整數,舉例:
BigInteger a=new BigInteger(“2222222222222222”);


既然不是基本數據類型,所以大數的加減乘除也不能使用+、-、*、/這些運算符號,Java也沒有對這些運算符號進行重定義,取而代之的是用一些方法來代替,比如add()、subtract()、mutiply()、divide()這四種方法,它們的使用舉例如下:

BigInteger使用舉例
那麼來總結一下BigInteger爲我們提供的常用的方法:

BigInteger abs()  返回大整數的絕對值
BigInteger add(BigInteger val) 返回兩個大整數的和
BigInteger and(BigInteger val)  返回兩個大整數的按位與的結果
BigInteger andNot(BigInteger val) 返回兩個大整數與非的結果
BigInteger divide(BigInteger val)  返回兩個大整數的商
double doubleValue()   返回大整數的double類型的值
float floatValue()   返回大整數的float類型的值
BigInteger gcd(BigInteger val)  返回大整數的最大公約數
int intValue() 返回大整數的整型值
long longValue() 返回大整數的long型值
BigInteger max(BigInteger val) 返回兩個大整數的最大者
BigInteger min(BigInteger val) 返回兩個大整數的最小者
BigInteger mod(BigInteger val) 用當前大整數對val求模
BigInteger multiply(BigInteger val) 返回兩個大整數的積
BigInteger negate() 返回當前大整數的相反數
BigInteger not() 返回當前大整數的非
BigInteger or(BigInteger val) 返回兩個大整數的按位或
BigInteger pow(int exponent) 返回當前大整數的exponent次方
BigInteger remainder(BigInteger val) 返回當前大整數除以val的餘數
BigInteger leftShift(int n) 將當前大整數左移n位後返回
BigInteger rightShift(int n) 將當前大整數右移n位後返回
BigInteger subtract(BigInteger val)返回兩個大整數相減的結果
byte[] toByteArray(BigInteger val)將大整數轉換成二進制反碼保存在byte數組中
String toString() 將當前大整數轉換成十進制的字符串形式

BigInteger xor(BigInteger val) 返回兩個大整數的異或



示例:

public static final BigInteger p = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);
public static final BigInteger a = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16);
public static final BigInteger b = new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16);
public static final BigInteger n = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);
public static final BigInteger Gx = new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16);
public static final BigInteger Gy = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16);
public static void main(String[] args) {
// BigInteger a = new BigInteger("666666666666");
// BigInteger b = new BigInteger("222222222222");
BigInteger add = a.add(b);
BigInteger subtract = a.subtract(b);
BigInteger modInverse = a.multiply(b);
BigInteger divide = a.divide(b);
System.out.println(add);
System.out.println(subtract);
System.out.println(modInverse);
System.out.println(divide);
}

發佈了70 篇原創文章 · 獲贊 64 · 訪問量 51萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章