Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining Powers of 2?

I am creating a simple bracket system and I need a way to check if there are a correct number of teams, OR if my program needs to compensate for bye rounds.

Right now, I am checking for "powers of two" with this function:

function validBracket(data) {
    var x = data.teams.length;
    return ((x != 0) && !(x & (x - 1)));
}

This works pretty well, but I am needing to know how many Bye rounds to add. For instance, if I had 16 teams, I would not need to add anymore teams. However, if I had 12 teams, I would need the first 4 teams to get a bye round.

How can I calculate number of bye rounds to add to my bracket? And would hard-coding an array of powers of two be better?

In pseudo code, something like this is what i was thinking of:

if(validateBracket(data)) {
    // Valid number of teams (power of two). Keep going.
} else {
    var byeRounds = calculateByeRounds();
}

NOTE: I would rather not use an array of powers of two like below:

var powersOfTwo = [2,4,8,16,32,...];

The reasoning behind this is that I would be limiting the number of teams that could be put in the system (however, I don't think a person would have over 256 teams).

like image 797
Hunter Mitchell Avatar asked Jun 14 '15 02:06

Hunter Mitchell


People also ask

What is the easiest way to calculate power of 2?

When multiplying 2x × 2y, remember that you simply add the exponents together. For example, 23 (8) × 27 (128) = 27+3 = 210 (1024). Similarly, you can break up a single power of 2 into two powers which add up to the original power, such as 29 (512) = 26+3 = 26 (64) × 23 (8).

How do you know if a number is a power of 2 in binary?

A power of two, when expressed in binary, will always look like 1 followed by n zeroes where n is greater than or equal to 0. Ex: Decimal Binary 1 1 (1 followed by 0 zero) 2 10 (1 followed by 1 zero) 4 100 (1 followed by 2 zeroes) 8 1000 (1 followed by 3 zeroes) . . . . . .


1 Answers

var needed = (1 << Math.ceil(Math.log2(n))) - n;

More generalized solution for extreme cases:

var needed = Math.pow(2, Math.ceil(Math.log2(n))) - n;
like image 88
Amadan Avatar answered Sep 19 '22 04:09

Amadan