大数字方法

时间:2016-08-03 13:50:28

标签: java biginteger

我无法弄清楚为什么,但是当使用幂函数时,它会在答案的中间添加一个(似乎是随机的)整数。我无法弄清楚为什么,你们有没有看到任何异常的东西?感谢

yii2

2 个答案:

答案 0 :(得分:2)

请尝试以下代码:

BigInteger number1 = new BigInteger("5");
System.out.println("Result = " + number1.pow(5).toString());

我们是如何在java中完成的。

答案 1 :(得分:0)

有一个用于在Java中使用权限的库,即Math.pow(对于小数字)和BigInteger pow(对于任意大数字)。请注意,BigInteger功率无法计算分数功率。

还有用于分数幂的迭代DIY算法,例如

BigInteger sqrt(BigInteger n) {
  BigInteger a = BigInteger.ONE;
  BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")).toString());
  while(b.compareTo(a) >= 0) {
    BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString());
    if(mid.multiply(mid).compareTo(n) > 0) b = mid.subtract(BigInteger.ONE);
    else a = mid.add(BigInteger.ONE);
  }
  return a.subtract(BigInteger.ONE);
}
相关问题