大数问题
Java中有两个类BigDecimal(表示浮点数)和BigInteger(表示整数)
使用这两个类的时候需要加上import java.math.*;
Ⅰ基本函数:
(1)valueOf(parament); 将参数转换为指定类型
例如:
int a = 3;
BigInteger b = BigInteger.valueOf(a);
即b = 3
String s = “1234”;
BigInteger b = BigInteger.valueOf(s);
即b = 1234
(2)add(); //大数加法
例如:
BigInteger a = new BigInteger(“11”);
BigInteger b = new BigInteger(“22”);
a.add(b);
即a = 33
(3)substract(); //减法
(4)multiply(); //乘法
(5)pided(); //相除取整
(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)BigIntergerde 构造函数
一般用到以下两种:
BigInteger(String val);
将指定字符串转换为十进制表示形式;
BigInteger(String val,int radix);
将指定基数的 BigInteger 的字符串表示形式转换为 BigInteger
例如:
BigInteger b = new BigInteger("1010",2);
System.out.println(b);
输出:10
Ⅱ.基本常量:
A=BigInteger.ONE //=1
B=BigInteger.TEN //=10
C=BigInteger.ZERO //=0
Ⅲ.基本操作
1. 读入:while(cin.hasNext()) //等同于!=EOF
{
int n;
BigInteger m;
n=cin.nextInt(); //读入一个int;
m=cin.BigInteger();//读入一个BigInteger;
System.out.print(m.toString());
System.out.print(m);
}
Ⅳ.运用
四则预算: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.pide(b1, c, 4);
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);
}
}
}
}