开发者

C# math question: smallest power of 2 bigger than X?

开发者 https://www.devze.com 2023-02-21 08:36 出处:网络
public int CalcBrackets(int teamCount) { int positions = 1; while (positions < teamCount) positions *= 2;
    public int CalcBrackets(int teamCount)
    {
        int positions = 1;

        while (positions < teamCount)
            positions *= 2;

        return positions;
    }

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 :(


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 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);
}

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.


That while loop doesn't go over multiples of two, but rather powers of two.

If u really need the multiple just add 1, divide by 2 to get the half part and then multiply back by two:

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

so that if it was even then you obtain back the same nuber, while if it was odd, since you add 1 and then divide, you get the next even number.


Smallest multiple

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

Smallest power, you can take the log. Something like

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

For suitable ceil and log_2 functions. Your technique is fine though.


this way is simple enough:

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


Not bigger smaller and if you mean multiple 2*2*2*2* log aritm best way that is use logaritma function in base 2 and round result to lower base.That is if team count equals 35 log 2 base 35 gives you 5,xxx round it to 5.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号