Help creating "Halving" Equation

1.1k Views Asked by At

I am not sure if this is the correct site to ask this but here goes,

I have a pseudocode for a program algorithm that I am trying to turn into an equation.

Say I have a variable X. Now if X is 8, the halving would be 8, 4, 2, 1 which is 4 levels.

So, right now I have that if X is a power of two the number of levels would just be X/2

My problem is that I do not know if X will be a power of two every time and I cannot have fractions (need to take the ceiling).

For example, If X = 9, the first "half" would be 4.5 -> 5, the next "half" would be 2.5 -> 3, again would result in 1.5->2, and then finally 1. Which would give me 5 levels (9,5,3,2,1).

Now, I have found a trend but I am having problems turning it into 1 equation.

X - Levels
2 - 2 (2 ,1)
3 - 3 (3 ,2,1)
4 - 3 (4 ,2,1)
5 - 4 (5 ,3,2,1)
6 - 4 (6 ,3,2,1)
7 - 4 (7 ,4,2,1)
8 - 4 (8 ,4,2,1)
9 - 5 (9 ,5,3,2,1)
10- 5 (10,5,3,2,1)
11- 5 (11,6,3,2,1)
12- 5 (12,6,3,2,1)
13- 5 (13,7,4,2,1)
14- 5 (14,7,4,2,1)
15- 5 (15,8,4,2,1)
16- 5 (16,8,4,2,1)
17- 6 (17,9,5,3,2,1)

As you can see there is only 1 value of X that results in two levels, 2 X's that result in 3 levels, 4 X's that result in 4 levels, 8 X's that result in 5 levels, and so on...

Could anyone help me figure out an equation given X, that would return me the correct number of levels?

1

There are 1 best solutions below

1
On BEST ANSWER

If $X$ is a power of $2$, the number of levels is $\log_2(X)+1$, not $X/2$. As you say $16$ has $5$ levels, not $8$.

For more general $X$, the number of levels is $\lceil \log_2(X) \rceil +1$, you just round the logarithm upward. Alternately, you can round $X$ up to the next power of $2$. Note that in your table the number of levels increments by $1$ each time $X$ goes above a power of $2$.