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

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

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

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

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

下面說說幾個經常使用的用法spa

1. code

   int a=3;對象

  BigInteger b=BigInteger.valueOf(a);blog

  則b=3;ip

2.ci

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 }
相關文章
相關標籤/搜索