用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());
}
Ⅳ.運用
四則預算:
import java.util.Scanner;
import java.math.*;
import java.text.*;
public class Main 
{
public static void main(String args[])
{
    Scanner cin = new Scanner ( System.in );
    BigInteger a,b;
    int c;
    char op;
    String s;

    while( cin.hasNext() )
    {
        a = cin.nextBigInteger();
        s = cin.next();
        op = s.charAt(0);
        if( op == '+')
        {
             b = cin.nextBigInteger();
             System.out.println(a.add(b));
        }
        else if( op == '-')
        {
             b = cin.nextBigInteger();
             System.out.println(a.subtract(b));
        }
        else if( op == '*')
        {
             b = cin.nextBigInteger();
             System.out.println(a.multiply(b));
        }
        else
        {
             BigDecimal a1,b1,eps;
             String s1,s2,temp;
             s1 = a.toString();
             a1 = new BigDecimal(s1);
             b = cin.nextBigInteger();
             s2 = b.toString();
             b1 = new BigDecimal(s2);
             c = cin.nextInt();
             eps = a1.divide(b1,c,4);
             //System.out.println(a + " " + b + " " + c);
             //System.out.println(a1.doubleValue() + " " + b1.doubleValue() + " " + c);
             System.out.print( a.divide(b) + " " + a.mod(b) + " ");
             if( c != 0)
             {
                  temp = "0.";
                  for(int i = 0; i < c; i ++) temp += "0";
                  DecimalFormat gd = new DecimalFormat(temp);
                  System.out.println(gd.format(eps));
             }
             else 
                 System.out.println(eps);
         }
     }
   }
}

———————————————————————————————————————————————
博客原址:http://blog.sina.com.cn/s/blog_64909ff901019a98.html

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