1. 程式人生 > >JAVA中處理大數方法彙總

JAVA中處理大數方法彙總

     在用C或者C++處理大數時感覺非常麻煩,但是在JAVA中有兩個類BigInteger和BigDecimal分別表示大整數類和大浮點數類,至於兩個類的物件能表示最大範圍不清楚,理論上能夠表示無線大的數,只要計算機記憶體足夠大。

這兩個類都在java.math.*包中,因此每次必須在開頭處引用該包。


Ⅰ基本函式:

1.valueOf(parament); 將引數轉換為制定的型別

比如 int a=3;

BigInteger b=BigInteger.valueOf(a);

則b=3;

String s=”12345”;

BigInteger c=BigInteger.valueOf(s);

則c=12345;


2.add(); 大整數相加

BigInteger a=new BigInteger(“23”);

BigInteger b=new BigInteger(“34”);

a. add(b);


3.subtract(); 相減

4.multiply(); 相乘

5.divide(); 相除取整

6.remainder(); 取餘

7.pow(); a.pow(b)=a^b

8.gcd(); 最大公約數

9.abs(); 絕對值

10.negate(); 取反數

11.mod(); a.mod(b)=a%b=a.remainder(b);

12.max(); min();

13.punlic int comareTo();

14.boolean equals(); 是否相等

15.BigInteger建構函式:

一般用到以下兩種:

BigInteger(String val);

將指定字串轉換為十進位制表示形式;

BigInteger(String val,int radix);

將指定基數的 BigInteger 的字串表示形式轉換為 BigInteger

Ⅱ.基本常量:

A=BigInteger.ONE 1

B=BigInteger.TEN 10

C=BigInteger.ZERO 0

Ⅲ.基本操作

1. 讀入:

用Scanner類定義物件進行控制檯讀入,Scanner類在java.util.*包中

Scanner cin=new Scanner(System.in);// 讀入

while(cin.hasNext()) //等同於!=EOF

{

int n;

BigInteger m;

n=cin.nextInt(); //讀入一個int;

m=cin.BigInteger();//讀入一個BigInteger;

System.out.print(m.toString());

}

if( a.compareTo(b) == 0 ) System.out.println("a == b"); //大整數a==b

else if( a.compareTo(b) > 0 ) System.out.println("a > b"); //大整數a>b

else if( a.compareTo(b) < 0 ) System.out.println("a < b"); //大整數a<b

//大整數絕對值

System.out.println(a.abs()); //大整數a的絕對值

//大整數的冪

int exponent=10;

System.out.println(a.pow(exponent)); //大整數a的exponent次冪

//返回大整數十進位制的字串表示

System.out.println(a.toString());

//返回大整數p進位制的字串表示

int p=8;

System.out.println(a.toString(p));