C#数学题: smallest power of 2 bigger than X?

标签 c# math

    public int CalcBrackets(int teamCount)
    {
        int positions = 1;

        while (positions < teamCount)
            positions *= 2;

        return positions;
    }

我想要大于或等于 teamCount 的 2 的幂的最小数字。这真的是最好的方法吗?它确实看起来很可怕:(

最佳答案

如果您需要计算小于 teamCount 的 2 的最小次方(不是倍数),那么这可能是最好的方法。取对数是一项代价高昂的操作,可能比简单的循环花费更多的时间。

更新 这是一个使用按位运算的算法 (C++)(http://aggregate.org/MAGIC/,下一个最大的 2 的幂部分)

unsigned int nlpo2(unsigned int x)
{
    x--; // comment out to always take the next biggest power of two, even if x is already a power of two
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
    return (x+1);
}

首先,它将数字的所有相关位设置为 1(例如,0x3ff),然后递增它 (0x400) 以获得 2 的幂。

关于C#数学题: smallest power of 2 bigger than X?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5525122/

相关文章:

c# - Web 应用程序中的 BeginGetResponse

c# - 什么是 [程序集 : Dependency()] in Xamarin?

algorithm - 给定一个整数,找到给定它的最小函数

python - numpy max vs amax vs 最大值

Java:帮助进行基本输出基本值算术。输出为0,不知道为什么?

c# - 将 C# .net 4 代码编译为 .net 3.5?

c# - 不能将可为空的小数添加到模型中

c# - 从 sql server 读取数据时检测到自引用循环

javascript - 如何将(一天的)秒数转换为文本?

javascript - 重力模拟中物体缓慢向右漂移