Quantify number of steps taken to reach $N$ if a variable $k$ is incremented in powers of 2

19 Views Asked by At

I have some java code as follows:

for(int k = 1; k < N; k = k * 2){
    foo();
}

How to estimate how many times foo() gets executed? It should be represented as some function of $N$...

Say for $N=10$, we get 4 executions: $k = 1, 2, 4, 8$

For $N=20$, we get 5 executions: $k = 1,2,4,8,16$

For $N = 30$, we get 5 executions: $k= 1,2,4,8,16$

1

There are 1 best solutions below

0
On

$k $ increases geometrically with powers of $2$. Solving for $n$ from the $n^{th}$ term.

$$ ar^{n-1} = N$$

Here $ a=1, r=2 $, solving for $ n $ we get $ n= 1 + \frac{log N}{log 2} $