Yesterday I applied for computer engineering master degree and it was the one of the their questions. I could not solve it so I was very curious.
...
i = 1;
while (i <= n)
{
i = i * 2;
}
...
How many times will this while loop get executed, please give your answer as a formula. For ex: log n…
Thanks
On the xth iteration of the loop,
iequals 2x (you can easily prove this by induction). Suppose the loop stops after X iterations, which means n < 2X. This also means that on iteration X-1 the loop was still running and so 2X-1 ≤ n. In other words :2X-1 ≤ n < 2X
From there, finding X as a function of log2(n) is easy.