BigInteger:以可扩展的方法计算小数位数

2024-04-20

我需要计算 a 的小数位数BigInteger。例如:

  • 99回报2
  • 1234回报4
  • 9999回报4
  • 12345678901234567890回报20

我需要这样做for a BigInteger with 184948小数位及更多. 我怎样才能快速且可扩展地做到这一点?

The 转换为字符串方法很慢:

public String getWritableNumber(BigInteger number) {
   // Takes over 30 seconds for 184948 decimal digits
   return "10^" + (number.toString().length() - 1);
}

This 循环除以十方法甚至更慢:

public String getWritableNumber(BigInteger number) {
    int digitSize = 0;
    while (!number.equals(BigInteger.ZERO)) {
        number = number.divide(BigInteger.TEN);
        digitSize++;
    }
    return "10^" + (digitSize - 1);
}

有没有更快的方法?


这是一种基于的快速方法达里乌斯的回答 https://stackoverflow.com/a/18828536/319821:

public static int getDigitCount(BigInteger number) {
  double factor = Math.log(2) / Math.log(10);
  int digitCount = (int) (factor * number.bitLength() + 1);
  if (BigInteger.TEN.pow(digitCount - 1).compareTo(number) > 0) {
    return digitCount - 1;
  }
  return digitCount;
}

以下代码测试数字 1、9、10、99、100、999、1000 等,一直到一万位:

public static void test() {
  for (int i = 0; i < 10000; i++) {
    BigInteger n = BigInteger.TEN.pow(i);
    if (getDigitCount(n.subtract(BigInteger.ONE)) != i || getDigitCount(n) != i + 1) {
      System.out.println("Failure: " + i);
    }
  }
  System.out.println("Done");
}

这可以检查一个BigInteger with 184,948十进制数字甚至更多的时间都在不到一秒的时间内。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

BigInteger:以可扩展的方法计算小数位数 的相关文章

随机推荐