Java 大整数类的应用 模板

这里记录一下Java的大整数一些操作:

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

public class bigint {

	public static void main(String[] args) {
		String s1,s2;
		Scanner sc = new Scanner(System.in);
		s1=sc.nextLine();
		//大数操作 BigInteger
		BigInteger big1 = new BigInteger(s1);
		BigInteger big2 = new BigInteger("2");
		System.out.println("加法:"+big1.add(big2)); 
		System.out.println("减法:"+big1.subtract(big2));
		System.out.println("乘法:"+big1.multiply(big2));
		System.out.println("除法:"+big1.divide(big2));
		BigInteger res[]=big1.divideAndRemainder(big2);
		System.out.println("商是:"+res[0]+";余数是:"+res[1]);
		
		//大小数操作 BigDecimal
		s2=sc.nextLine();
		BigDecimal decimal1 = new BigDecimal(s2);
		BigDecimal decimal2 = new BigDecimal("3.333");
		System.out.println("加法:"+decimal1.add(decimal2));
		System.out.println("减法:"+decimal1.subtract(decimal2));
		System.out.println("乘法:"+decimal1.multiply(decimal2));
		System.out.println("除法:"+decimal1.divide(decimal2,5,BigDecimal.ROUND_HALF_UP));
		//JAVA中如果用BigDecimal做除法的时候一定要在divide方法中传递第二个参数,定义精确到小数点后几位,第三个是四舍五入
		//否则在不整除的情况下,结果是无限循环小数时,就会抛出以上异常。
	}

}

例题:

import java.math.BigInteger;

public class ceshi {

	public static void main(String[] args) {
		//求3+33+333+.....+3333..(20个3的和)
		String s="";
		BigInteger sum = new BigInteger("0");
		for(int i=0;i<20;i++) {
			s+='3';
		BigInteger ss=new BigInteger(s);
		   sum=sum.add(ss);
		}
		System.out.println(sum);//37037037037037037030
	}
}

 

你可能感兴趣的:(java,模板)