java 高精度 四则运算

时间:2022-02-06 02:21:14

java的大数处理对于ACM中的大数来说,相当的简单啊;

整数的运算   BigInteger

小数的运算   BigDecimal

导入类:

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

java 大数相除不能整除时会抛出异常,解决办法,设置精度;参见:java之BigDecimal

 num1 = num1.divide(num2,10,BigDecimal.ROUND_HALF_EVEN);
System.out.println(num1);

算阶乘时也可用;

需要转化一下

 int n = cin.nextInt() ;
BigInteger m = BigInteger.valueOf(1) ;
for(int i = 1;i<=n;i++){
m = m.multiply(BigInteger.valueOf(i)) ;//int 整形转化为 BigInteger 进行计算
}
System.out.println(m);

//输入两个大数进行加法运算  add() 相加

 import java.util.Scanner;
import java.math.BigInteger;
public class dashu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BigInteger a,b;
a=input.nextBigInteger();
b=input.nextBigInteger();
System.out.println(a.add(b));
}
}

//输入两个大数相减  subtract ()  相减

 import java.util.*;
import java.math.BigInteger;
public class dashu {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
BigInteger num1 = input.nextBigInteger();
BigInteger num2 = input.nextBigInteger();
System.out.println(num1.subtract(num2));
}
}

//输入两个大数相乘  mulitiply () 相乘

 import java.util.* ;
import java.math.BigInteger ;
public class dashu {
public static void main(String[] args) {
Scanner input = new Scanner(System.in) ;
BigInteger m,n;
m=input.nextBigInteger();
n=input.nextBigInteger();
m = m.multiply(n) ;
System.out.println(m);
}
}

//两个大数相除 divide()  相除   remainder()  余数

 import java.util.*;
import java.math.BigInteger;
public class dashu {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
BigInteger num1 = input.nextBigInteger();
BigInteger num2 = input.nextBigInteger();
System.out.println(num1.divide(num2));//相除
System.out.println(num1.remainder(num2));//余数
}
}