C#数学问题:2的最小幂大于X?

public int CalcBrackets(int teamCount) { int positions = 1; while (positions < teamCount) positions *= 2; return positions; } 

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

如果你需要计算的最小功率2(不是倍数)小于teamCount,那么可能它是最好的方法。 采用对数是一项算术运算,可以花费更多时间进行简单的循环。

upd这是一个使用按位运算的算法(C ++)(http://aggregate.org/MAGIC/,Sext 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); } 

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

while循环不会超过2的倍数,而是2的幂。

如果你真的需要倍数只需加1,除以2得到半部分然后再乘以2:

 return ((teamCount+1)/2)*2 

所以,如果它甚至那么你获得了相同的nuber,而如果它是奇数,因为你加1然后除,你得到下一个偶数。

最小的倍数

 return (teamCount % 2 == 0 ? teamCount : teamCount + 1); 

最小的功率 ,你可以记录日志。 就像是

 2 ** (ceil(log_2(teamCount))) 

适用于ceil和log_2function。 你的技术很好。

这种方式很简单:

 if (teamCount % 2 == 0) return teamCount; else return (teamCount + 1); 

不大更小,如果你的意思是多个2 * 2 * 2 * 2 * log aritm最好的方法是使用基数2中的logaritma函数和圆形结果来降低base.That如果团队数等于35 log 2 base 35给你5, xxx将其四舍五入到5。