BigInteger bi = new BigInteger("1234567890"); System.out.println(bi.pow(5)); // 2867971860299718107233761438093672048294900000
对BigInteger做运算的时候,只能使用实例方法,例如,加法运算:
1 2 3
BigInteger i1 = new BigInteger("1234567890"); BigInteger i2 = new BigInteger("12345678901234567890"); BigInteger sum = i1.add(i2); // 12345678902469135780
和long型整数运算比,BigInteger不会有范围限制,但缺点是速度比较慢。
也可以把BigInteger转换成long型:
1 2 3
BigInteger i = new BigInteger("123456789000"); System.out.println(i.longValue()); // 123456789000 System.out.println(i.multiply(i).longValueExact()); // java.lang.ArithmeticException: BigInteger out of long range
BigDecimal n = new BigDecimal("12.75"); BigDecimal m = new BigDecimal("0.15"); BigDecimal[] dr = n.divideAndRemainder(m); if (dr[1].signum() == 0) { // n是m的整数倍 }
publicstaticvoidjichengint(){ int result = 1; for (int i = 1; i <= 100; i++) { result *= i; } System.out.println("阶乘Int: "+result); }
publicstaticvoidjiechengbiginteger(){ BigInteger result = new BigInteger("1");//为result赋初始值,为1 for (int i = 1; i <= 100; i++) { BigInteger num = new BigInteger(String.valueOf(i)); result = result.multiply(num);//调用自乘方法 } System.out.println("阶乘BigInTeger "+result);//输出结果 System.out.println("位数: "+String.valueOf(result).length());//输出长度 }
publicstaticvoidjiechengbigdecimal(){ //求一百的阶乘之和 //只能用math里边的BigDecimal来存储数据 //定义变量保存阶乘的和 BigDecimal result = new BigDecimal("1");//为result赋初始值,为1 for (int i = 1; i <= 100; i++) { BigDecimal num = new BigDecimal(String.valueOf(i)); result = result.multiply(num);//调用自乘方法 } System.out.println("阶乘BigDecimal "+result);//输出结果 System.out.println("位数: "+String.valueOf(result).length());//输出长度 }