ACM常见高精度总结(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.public int compareTo();

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.nextBigInteger();//读入一个BigInteger;
 System.out.print(m);
}

Ⅳ.运用

四则预算:

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main  
{  
	public static void main(String args[])  
	{
		Scanner sca = new Scanner(System.in);
		BigInteger a,b;
		int c;//为小数设置精度
		char op;//运算符
		String s;
		while(sca.hasNext()){
			a = sca.nextBigInteger();
			s = sca.next();
			op = s.charAt(0);
			b = sca.nextBigInteger();
			if(op == '+')
				System.out.println(a.add(b));
			else if(op == '-')
				System.out.println(a.subtract(b));
			else if(op == '*')
				System.out.println(a.multiply(b));
			else{
				BigDecimal t1,t2,eps;
				String s1,s2,temp;
				s1 = a.toString();
				s2 = b.toString();
				t1 = new BigDecimal(s1);
				t2 = new BigDecimal(s2);
				c = sca.nextInt();
				eps = t1.divide(t2,c,4);
				//System.out.println(a + " " + b + " " + c);  
			    //System.out.println(t1.doubleValue() + " " + t2.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);
			}
		}
	}
}
  
//=====================================================================================//  
charAt
public char charAt(int index)

Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. 
If the char value specified by the index is a surrogate, the surrogate value is returned.


divide
public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode)

Returns a BigDecimal whose value is (this / divisor), and whose scale is as specified. If rounding must be performed to generate a result with the specified scale, the specified rounding mode is applied. 


public DecimalFormat(String pattern)
Creates a DecimalFormat using the given pattern and the symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.
To obtain standard formats for a given locale, use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale.


hdu1002

http://acm.hdu.edu.cn/showproblem.php?pid=1002

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);
    	int T = sca.nextInt(),t = 1;
    	while(t <= T){
    		BigInteger a,b;
    		a = sca.nextBigInteger();
    		b = sca.nextBigInteger();
    		BigInteger c = a.add(b);
    		System.out.println("Case "+ t + ":");
    		System.out.println(a + " + " + b + " = " + c);
    		if(t != T)
    			System.out.println("");
    		t++;
    	}
	}
}

 
 hdu1042 
 

http://acm.hdu.edu.cn/showproblem.php?pid=1042

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);  
		BigInteger a[] = new BigInteger[10005];
		a[0] = BigInteger.ONE;
		for(int i = 1; i <= 10000; i++)
			a[i] = a[i - 1].multiply(BigInteger.valueOf(i));
		int n;
		while(sca.hasNextInt()){
			n = sca.nextInt();
			System.out.println(a[n]);
		}
	}
}

hdu1047

http://acm.hdu.edu.cn/showproblem.php?pid=1047

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		 Scanner sca = new Scanner(System.in);
		 int T = sca.nextInt(), t = 1;
		 while(t <= T){
			 BigInteger sum = BigInteger.ZERO;
			 BigInteger zero =  BigInteger.ZERO;
			 BigInteger tmp;
			 while(sca.hasNextBigInteger()){
				 tmp = sca.nextBigInteger();
				 if(tmp.equals(zero))
					 break;
				 else
					 sum = sum.add(tmp);
			 }
			 System.out.println(sum);
			 if(t != T)
				 System.out.println();
			 t++;
		 }
	}
}

hdu1063

http://acm.hdu.edu.cn/showproblem.php?pid=1063

import java.math.BigDecimal;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);
		 BigDecimal R,sum;
		 int n;
		 while(sca.hasNextBigDecimal()){
			 sum = BigDecimal.ONE;
			 R = sca.nextBigDecimal();
			 n = sca.nextInt();
			 for(int i = 1; i <= n; i++)
				 sum = sum.multiply(R);
			 sum = sum.stripTrailingZeros();
			 String str = sum.toPlainString();
			 if(str.startsWith("0."))
				 str = str.substring(1);
			 System.out.println(str);
		 }
	}
}

stripTrailingZeros
public BigDecimal stripTrailingZeros()

Returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. For example, stripping the trailing zeros from the BigDecimal value 600.0, which has [BigInteger, scale] components equals to [6000, 1], yields 6E2 with [BigInteger, scale] components equals to [6, -2]
Returns:a numerically equal BigDecimal with any trailing zeros removed.


toPlainString
public String toPlainString()

Returns a string representation of this BigDecimal without an exponent field. For values with a positive scale, the number of digits to the right of the decimal point is used to indicate scale. For values with a zero or negative scale, the resulting string is generated as if the value were converted to a numerically equal value with zero scale and as if all the trailing zeros of the zero scale value were present in the result. The entire string is prefixed by a minus sign character '-' ('\u002D') if the unscaled value is less than zero. No sign character is prefixed if the unscaled value is zero or positive. Note that if the result of this method is passed to the string constructor, only the numerical value of this BigDecimal will necessarily be recovered; the representation of the new BigDecimal may have a different scale. In particular, if this BigDecimal has a negative scale, the string resulting from this method will have a scale of zero when processed by the string constructor. (This method behaves analogously to the toString method in 1.4 and earlier releases.)
Returns:
a string representation of this BigDecimal without an exponent field.

startsWith
public boolean startsWith(String prefix)

Tests if this string starts with the specified prefix.
Parameters:prefix - the prefix.Returns:true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.


hdu1316

http://acm.hdu.edu.cn/showproblem.php?pid=1316

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);
		 int i,sum;
		 BigInteger a,b;
		 BigInteger f[] = new BigInteger[505];
		 BigInteger zero = BigInteger.ZERO;
		 f[1] = new BigInteger("1");
		 f[2] = new BigInteger("2");
		 for(i = 3; i <= 500; i++)
			 f[i] = f[i - 1].add(f[i - 2]);
		 while(sca.hasNextBigInteger()){
			 sum = 0;
			 a = sca.nextBigInteger();
			 b = sca.nextBigInteger();
			 if(a.equals(zero) && b.equals(zero))
				 break;
			 for(i = 1; i <= 500; i++){
				 if(a.compareTo(f[i]) <= 0 && b.compareTo(f[i]) >= 0)
					 sum++;
				 if(b.compareTo(f[i]) < 0)
					 break;
			 }
			 System.out.println(sum);
		 }
	}
}

hdu1715

http://acm.hdu.edu.cn/showproblem.php?pid=1715

import java.math.BigInteger;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);
		 int t = 1, T = sca.nextInt();
		 BigInteger f[] = new BigInteger[1005];
		 f[1] = f[2] = BigInteger.ONE;
		 for(int i = 3; i <= 1000; i++)
			 f[i] = f[i - 1].add(f[i - 2]);
		 while(sca.hasNext()){
			 int n = sca.nextInt();
			 System.out.println(f[n]);
		 }
	}
}

hdu1753

http://acm.hdu.edu.cn/showproblem.php?pid=1753

import java.math.BigDecimal;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);
		 BigDecimal a,b,c;
		 while(sca.hasNext()){
			 a = sca.nextBigDecimal();
			 b = sca.nextBigDecimal();
			 c = a.add(b);
			 c = c.stripTrailingZeros();
			 String str = c.toPlainString();
			 if(str.startsWith("0."))
				 str = str.substring(1);
			 System.out.println(str);
		 }
	}
}


你可能感兴趣的:(高精度,大数)