C#中的数学问题:2最小功率大于x? [英] C# math question: smallest power of 2 bigger than X?
问题描述
public int CalcBrackets(int teamCount)
{
int positions = 1;
while (positions < teamCount)
positions *= 2;
return positions;
}
我想是2和大于或等于电源的最小数teamCount。这真的是做到这一点的最好方法是什么?它看起来很可怕:(
I want the smallest number that is a power of 2 and bigger or equal than teamCount. Is this really the best way to do it? It sure looks horrible :(
推荐答案
如果你需要计算的2最少的功率(而不是多个)较小的话teamCount,然后可能是最好的方法。以对数是costy操作,可以把更多的时间,那么一个简单的循环。
If you need to calculate the least power of 2 (not the multiple) smaller then teamCount, then possibly it is the best way. Taking logarithm is a costy operation and can take more time then a simple cycle.
UPD
给一个算法使用位操作(C ++)(http://aggregate.org/MAGIC/,节下一个最大的2电源)
upd Here is an algorithm (C++) using bitwise operations (http://aggregate.org/MAGIC/, section Next Largest Power of 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);
}
首先,它设置数与那些所有相关的位(例如,为0x3FF),然后递增它(0x400的),以获得两个电源。
First, it sets all relevant bits of the number to ones (for example, 0x3ff) and then increments it (0x400) to get the power of two.
这篇关于C#中的数学问题:2最小功率大于x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!