栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

这看起来像在工作。我还没有进行详尽的测试,也没有进行任何时间的测试,但似乎运行时间合理。

public class Test {    private int log10(BigInteger huge) {    int digits = 0;    int bits = huge.bitLength();    // Serious reductions.    while (bits > 4) {      // 4 > log[2](10) so we should not reduce it too far.      int reduce = bits / 4;      // Divide by 10^reduce      huge = huge.divide(BigInteger.TEN.pow(reduce));      // Removed that many decimal digits.      digits += reduce;      // Recalculate bitLength      bits = huge.bitLength();    }    // Now 4 bits or less - add 1 if necessary.    if ( huge.intValue() > 9 ) {      digits += 1;    }    return digits;  }  // Random tests.  Random rnd = new Random();  // Limit the bit length.  int maxBits = BigInteger.TEN.pow(200000).bitLength();  public void test() {    // 100 tests.    for (int i = 1; i <= 100; i++) {      BigInteger huge = new BigInteger((int)(Math.random() * maxBits), rnd);      // Note start time.      long start = System.currentTimeMillis();      // Do my method.      int myLength = log10(huge);      // Record my result.      System.out.println("Digits: " + myLength+ " Took: " + (System.currentTimeMillis() - start));      // Check the result.      int trueLength = huge.toString().length() - 1;      if (trueLength != myLength) {        System.out.println("WRONG!! " + (myLength - trueLength));      }    }  }  public static void main(String args[]) {    new Test().test();  }}

在我的Celeron M笔记本电脑上花了大约3秒钟,因此它在某些不错的工具包上应该不到2秒钟。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495625.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号