BigInteger.pow(BigInteger)? [英] BigInteger.pow(BigInteger)?

查看:27
本文介绍了BigInteger.pow(BigInteger)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 玩数字,想看看我能做出多大的数字.我的理解是 BigInteger 可以容纳无限大小的数字,只要我的计算机有足够的内存来容纳这样的数字,对吗?

I'm playing with numbers in Java, and want to see how big a number I can make. It is my understanding that BigInteger can hold a number of infinite size, so long as my computer has enough Memory to hold such a number, correct?

我的问题是 BigInteger.pow 只接受一个 int,而不接受另一个 BigInteger,这意味着我只能使用最大为 2,147,483,647 的数字作为指数.是否可以这样使用 BigInteger 类?

My problem is that BigInteger.pow accepts only an int, not another BigInteger, which means I can only use a number up to 2,147,483,647 as the exponent. Is it possible to use the BigInteger class as such?

BigInteger.pow(BigInteger)

谢谢.

推荐答案

你可以自己写,使用 repeated平方:

You can write your own, using repeated squaring:

BigInteger pow(BigInteger base, BigInteger exponent) {
  BigInteger result = BigInteger.ONE;
  while (exponent.signum() > 0) {
    if (exponent.testBit(0)) result = result.multiply(base);
    base = base.multiply(base);
    exponent = exponent.shiftRight(1);
  }
  return result;
}

可能不适用于负底数或指数.

might not work for negative bases or exponents.

这篇关于BigInteger.pow(BigInteger)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆