大整形BigInteger,大数

大整形BigInteger

基本类型int有32位,范围是:[-2147483648, 2147483647](正负21亿多)
基本类型long有64位,范围是:[-9223372036854775808, 9223372036854775807]

虽然double可以表示更大的范围,但是却不是精确的整数。因此当需要使用到超出范围的整数时,就需要“大整形”。Java 中的大整形类java.math.BigInteger没有范围限制,使用方法如下:

BigInteger的创建:

CopyBigInteger bi1 = new BigInteger("123");
BigInteger bi2 = BigInteger.valueOf(234L);

BigInteger zero = BigInteger.ZERO;
BigInteger one = BigInteger.ONE;
BigInteger ten = BigInteger.TEN;

BigInteger的输入输出:

Copy// 控制台读入大整数
Scanner scanner = new Scanner(System.in);
BigInteger bi3 = scanner.nextBigInteger();
BigInteger bi4 = new BigInteger(scanner.nextLine());
// 控制台输出
System.out.println(bi1);
System.out.println(bi1.toString()); // 10进制
System.out.println(bi1.toString(2)); // 2进制
// 二进制位数
int len = bi1.bitLength();

BigInteger的比较:

Copyboolean equals = bi1.equals(bi2);
int cmp = bi1.compareTo(bi2);

BigInteger的运算:

Copy// 加
BigInteger sum = bi1.add(bi2);
// 减
BigInteger sub = bi1.subtract(bi2);
// 乘
BigInteger mul = bi1.multiply(bi2);
// 除
BigInteger div = bi1.divide(bi2);
// 取余
BigInteger mod = bi1.remainder(bi2);
// 除数与余数 result[0]是商,result[1]是余数
BigInteger[] result = bi1.divideAndRemainder(bi2);
// 幂
BigInteger pow = bi1.pow(4);
// 相反数
BigInteger neg = bi1.negate();
// 绝对值
BigInteger abs = bi1.abs();
// 最大公约数
BigInteger gcd = bi1.gcd(bi2);

BigInteger转换为基本类型:

Copybyte byteValue = bi1.byteValue();
byte byteValueExact = bi1.byteValueExact();
short shortValue = bi1.shortValue();
short shortValueExact = bi1.shortValueExact();
int intValue = bi1.intValue();
int intValueExact = bi1.intValueExact();
long longValue = bi1.longValue();
long longValueExact = bi1.longValueExact();
float floatValue = bi1.floatValue();
double doubleValue = bi1.doubleValue();

其中,大整形超出相应基本类型时截断高位,超出浮点型的范围时为InfinityxxxValueExact()方法则是抛出ArithmeticException异常。

  • 例子:求2021的阶乘。

分析:2021的阶乘结果非常大,超出了long,可借助java中的大数。

public static void main(String[] args) {
		
		BigInteger i = new BigInteger("1");
		BigInteger begin = new BigInteger("1");
		BigInteger max = new BigInteger("2021");
		BigInteger ans = new BigInteger("1");
		
		while(i.equals(max) == false){
	    	ans = ans.multiply(i);
	    	i = i.add(begin);
		}
		ans = ans.multiply(i);
       System.out.println(ans);
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值