1. 程式人生 > >JAVA 大數類

JAVA 大數類

port ner sca compare pla 大數相乘 lai 高精 學習

碰到很多大數類的題目,聽說JAVA比較流氓,趕緊去學習一波( <(?????)> )

大數相加:

 1 //JAVA 大數相加 
 2 import java.math.BigInteger;
 3 import java.util.*;
 4 import java.io.*;
 5 
 6 public class Main
 7 {
 8     public static void main(String args[])
 9     {
10         Scanner cin = new Scanner(System.in);
11             BigInteger a = cin.nextBigInteger();
12 BigInteger b = cin.nextBigInteger(); 13 BigInteger ans = a.add(b); 14 System.out.println(ans); 15 } 16 }

大數相乘:

 1 //JAVA 大數相乘 
 2 import java.math.BigInteger;
 3 import java.util.*;
 4 import java.io.*;
 5 
 6 public class Main
 7 {
 8     public
static void main(String args[]) 9 { 10 Scanner cin = new Scanner(System.in); 11 BigInteger a = cin.nextBigInteger(); 12 BigInteger b = cin.nextBigInteger(); 13 BigInteger ans = a.multiply(b); 14 System.out.println(ans); 15 } 16
}

大數相減:public BigInteger subtract(BigInteger val)

大數相除:public BigInteger divide(BigInteger val)

大數階乘:

 1 //JAVA 大數階乘 
 2 import java.io.*;
 3 import java.math.BigInteger;
 4 import java.util.*;
 5 
 6 public class Main
 7 {
 8     public static void main(String args[])
 9     {
10         Scanner cin = new Scanner(System.in);    
11         int n = cin.nextInt(); //輸入int型 
12         BigInteger ans = BigInteger.ONE;
13         for(int i = 1; i <= n; i++)
14         ans = ans.multiply(BigInteger.valueOf(i));
15         System.out.println(ans);
16     }
17 }

大數比較大小

 1 //JAVA 大數比較大小 
 2 import java.io.*;
 3 import java.math.BigInteger;
 4 import java.util.*;
 5 
 6 public class Main
 7 {
 8     public static void main(String args[])
 9     {
10         Scanner cin = new Scanner(System.in);    
11         while(cin.hasNext())
12         {
13             BigInteger a = cin.nextBigInteger();
14             BigInteger b = cin.nextBigInteger();
15             if(a.equals(BigInteger.ZERO) && b.equals(BigInteger.ZERO)) break;
16             int flag = a.compareTo(b);
17             if(flag == -1)
18                 System.out.println("a<b");
19             else if(flag == 0)
20                 System.out.println("a==b");
21             else
22                 System.out.println("a>b");
23         }
24     }
25 }

高精度冪

 1 //JAVA 高精度冪 
 2 import java.io.*;
 3 import java.math.BigDecimal;
 4 import java.util.*;
 5 
 6 public class Main
 7 {
 8     public static void main(String args[])
 9     {
10         Scanner cin = new Scanner(System.in);    
11         while(cin.hasNext())
12         {
13             BigDecimal ans = cin.nextBigDecimal();
14             int n = cin.nextInt();
15             String res = ans.pow(n).stripTrailingZeros().toPlainString(); //整數去掉後面的0和小數點 
16             if(res.startsWith("0")) //去掉前導0 
17             {
18                 res = res.substring(1);
19             }
20             System.out.println(res);
21         }
22     }
23 }

//這裏的BigDecimal相當於double,但是精度更高

JAVA 大數類