c# - 大量的 BigInteger 日志问题

标签 c# .net math biginteger logarithm

下面的代码采用 BigInteger n 并找到一个小于 n 的数,该数也是 2 的幂。它适用于小数字,但 if 语句的第一个分支不适用于 int.MaxValue 及更高版本。显然减去 1 (BigInteger.Log(n - 1)) 对于更大的数字是不够的。

我怎样才能计算出一个大到足以产生差异的数字来减去,同时还能处理较小的数字?

public BigInteger FindNearestPowerOfTwo (BigInteger n)
{
    double number = 0;
    BigInteger big = 0;

    if (n.IsPowerOfTwo)
    {
        number = BigInteger.Log(n - 1) / BigInteger.Log(2);
    }
    else
    {
        number = BigInteger.Log(n) / BigInteger.Log(2);
    }

    number = Math.Floor(number);

    big = BigInteger.Pow(2, (int) number);

    return (big);
}

最佳答案

您可以使用 ToByteArray 获得显式表示,然后清除除最高位以外的所有位。

public BigInteger FindNearestPowerOfTwo (BigInteger n) {
    Byte[] a = n.ToByteArray();
    int len = a.Length;
    if (a[len - 1] == 0) len--; // leading zero to maintain sign
    for (int i = 0; i < len - 1; i++) a[i] = 0;
    int x = a[len - 1] & 255;
    int y = 1;
    while (x > 1) {
      x >>= 1;
      y <<= 1;
    }
    a[len - 1] = y;
    return new BigInteger(a);
}

关于c# - 大量的 BigInteger 日志问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11677972/

相关文章:

c# - 尝试将图像保存到 MemoryStream 时 GDI+ 异常中发生一般错误

.net - 如何在 vb.net 中刷新 Datagridview

c# - 使用 "greater than or equals"或仅使用 "greater than"

c# - 从 IQueryable<T> 转换为 T

c# - 如何确定我的应用程序的控制台窗口何时获得或失去焦点?

algorithm - 数学公式的比较

javascript - JS 中的简单数学加法给出错误结果

c++ - 用于 vector 和矩阵计算的高性能数学库

c# - 使用运行时类型执行的通用方法

c# - 字典的匿名集合初始值设定项