大数字(Big Numbers)的使用

前几天写算法,用到Java中的大数字,尤其是BigInterger类。在《Core Java2》关于Big Numbers有如下经典的描述:

If the precision of the basic integer and floating-point types is not sufficient, you can turn to a couple of handy classes in the java.math package: BigInteger and BigDecimal. These are classes for manipulating numbers with an arbitrarily long sequence of digits. The BigInteger class implements arbitrary precision integer arithmetic, and BigDecimal does the same for floating-point numbers.

Use the static valueOf method to turn an ordinary number into a big number:

BigInteger a = BigInteger.valueOf(100);
Unfortunately, you cannot use the familiar mathematical operators such as + and * to combine big numbers. Instead, you must use methods such as add and multiply in the big number classes.
BigInteger c = a.add(b); // c = a + b
BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); // d = c * (b + 2)


API:java.math.BigInteger 1.1
  • BigInteger add(BigInteger other)

  • BigInteger subtract(BigInteger other)

  • BigInteger multiply(BigInteger other)

  • BigInteger divide(BigInteger other)

  • BigInteger mod(BigInteger other)

    return the sum, difference, product, quotient, and remainder of this big integer and other.

  • int compareTo(BigInteger other)

    returns 0 if this big integer equals other, a negative result if this big integer is less than other, and a positive result otherwise.

  • static BigInteger valueOf(long x)

    returns a big integer whose value equals x.

          读完以上内容,发现自己以前对BigInteger的使用并不理想,譬如关于将一个普通数字转换为大数字,只知道用BigInteger的构造方法实现,将数转化为字符串,再构造BigInteger,commits a folly!,实际上用valueOf轻松可以实现,唉……

P.S. 使用大数前,切记import java.math.*;







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值