Java BigInteger(大數,ACM比賽專用)


用c或者C++處理大數比較麻煩,於是決心學習一下JAVA中大數運算。

先下載一個eclipse,具體的用法去問度娘吧

JAVA中有兩個類BigIntegerBigDecimal分別表示大整數類和大浮點數類

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

下面說說幾個常用的用法

1. 

   int a=3;

  BigInteger b=BigInteger.valueOf(a);

  則b=3;

2.

String s="-123459999999999999999999";
BigInteger c=new BigInteger(s,10);

把字符串轉換成10進制的大數;

3.

BigInteger a=new BigInteger("234");
BigInteger b=new BigInteger("567");

System.out.println(a.add(b));

2個大數相加,a沒變。

subtract(); 相減   multiply(); 相乘   divide();    相除取整   remainder(); 取余  pow();   a.pow(b)=a^b  gcd();   最大公約數

abs(); 絕對值  negate(); 取反數  mod(); a.mod(b)=a%b=a.remainder(b);   max(); min();  boolean equals(); 是否相等

3.

讀入:

用Scanner類定義對象進行控制台讀入,Scanner類在java.util.*包中

Scanner cin=new Scanner(System.in);
while(cin.hasNext())//相當於EOF
{
int n;
BigInteger m;
n=cin.nextInt();
m=cin.nextBigInteger();
System.out.println(n);
System.out.println(m);
}

插入寫的代碼

 1 import java.math.BigInteger;
 2 import java.util.Scanner;
 3 public class hello {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7          //System.out.println("hello");
 8         //int num=3;
 9         //System.out.println("hell0"+num);
10        //int a=3;
11        //BigInteger b=BigInteger.valueOf(a);
12        //System.out.println(b);
13        //String s="-123459999999999999999999";
14        //BigInteger c=new BigInteger(s,10);
15        //BigInteger c=new BigInteger("12345"); 
16         //BigInteger a=new BigInteger("234");
17         //BigInteger b=new BigInteger("567");
18         //BigInteger c=a+b;
19         //subtract();
20         //multiply();
21         //divide();
22         //remainder();
23         //pow();
24         //gcd();
25         //System.out.println(a.add(b));
26         Scanner cin=new Scanner(System.in);
27         while(cin.hasNext())
28         {
29             //int n;
30             BigInteger m,n;
31             n=cin.nextBigInteger();
32             m=cin.nextBigInteger();
33             boolean coper=n.equals(m);
34             System.out.println(n);
35             System.out.println(m);
36             System.out.println(coper);
37         }
38        
39     }
40 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM