Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 数学问题:2的最小幂比X大? public int-CalcBrackets(int-teamCount) { int位置=1; while(职位_C#_Math - Fatal编程技术网

C# 数学问题:2的最小幂比X大? public int-CalcBrackets(int-teamCount) { int位置=1; while(职位

C# 数学问题:2的最小幂比X大? public int-CalcBrackets(int-teamCount) { int位置=1; while(职位,c#,math,C#,Math,我想要一个最小的数字,它是2的幂,大于或等于teamCount。这真的是最好的方法吗?看起来很可怕:(最小倍数 最小的力量,你可以拿着圆木 return (teamCount % 2 == 0 ? teamCount : teamCount + 1); 适用于ceil和log_2功能。不过您的技术很好。这种方法非常简单: 2 ** (ceil(log_2(teamCount))) 那个while循环不是2的倍数,而是2的幂 如果你真的需要倍数,只需加1,除以2得到一半,然后再乘以2: if

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

最小倍数

最小的力量,你可以拿着圆木

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

适用于ceil和log_2功能。不过您的技术很好。

这种方法非常简单:

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

那个
while
循环不是2的倍数,而是2的幂

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

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

因此,如果它是偶数,那么你得到相同的数字,而如果它是奇数,因为你加1,然后除以,你得到下一个偶数。

如果你需要计算2的最小幂(不是倍数)比团队计数小,这可能是最好的方法。取对数是一个昂贵的操作,可能比简单的循环花费更多的时间

upd 下面是一个使用位运算的算法(C++)(http://aggregate.org/MAGIC/,第二节最大功率2)


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

不要太大或太小,如果你的意思是多个2*2*2*2*log算术,最好的方法是在基数2中使用logaritma函数,并将结果舍入到较低的基数。也就是说,如果团队计数等于35,那么log2 base 35会给你5,xxx将其舍入到5。

你的代码返回2的最小幂。这是你想要的,还是你想要的smal如果x已经是2的幂,它将返回x,如果x=0,它将返回0,这不是2的幂!
if (teamCount % 2 == 0)
    return teamCount;
else
    return (teamCount + 1);
return ((teamCount+1)/2)*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);
}