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);
算阶乘时也可用;
需要转化一下
1 int n = cin.nextInt() ; 2 BigInteger m = BigInteger.valueOf(1) ; 3 for(int i = 1;i<=n;i++){ 4 m = m.multiply(BigInteger.valueOf(i)) ;//int 整形转化为 BigInteger 进行计算 5 } 6 System.out.println(m);
//输入两个大数进行加法运算 add() 想加
1 import java.util.Scanner; 2 import java.math.BigInteger; 3 public class dashu { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 BigInteger a,b; 7 a=input.nextBigInteger(); 8 b=input.nextBigInteger(); 9 System.out.println(a.add(b)); 10 } 11 }
//输入两个大数相减 subtract () 相减
1 import java.util.*; 2 import java.math.BigInteger; 3 public class dashu { 4 public static void main(String args[]) { 5 Scanner input = new Scanner(System.in); 6 BigInteger num1 = input.nextBigInteger(); 7 BigInteger num2 = input.nextBigInteger(); 8 System.out.println(num1.subtract(num2)); 9 } 10 } 11
//输入两个大数相乘 mulitiply () 相乘
1 import java.util.* ; 2 import java.math.BigInteger ; 3 public class dashu { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in) ; 6 BigInteger m,n; 7 m=input.nextBigInteger(); 8 n=input.nextBigInteger(); 9 m = m.multiply(n) ; 10 System.out.println(m); 11 } 12 }
//两个大数相除 divide() 相除 remainder() 余数
1 import java.util.*; 2 import java.math.BigInteger; 3 public class dashu { 4 public static void main(String args[]) { 5 Scanner input = new Scanner(System.in); 6 BigInteger num1 = input.nextBigInteger(); 7 BigInteger num2 = input.nextBigInteger(); 8 System.out.println(num1.divide(num2));//相除 9 System.out.println(num1.remainder(num2));//余数 10 } 11 } 12