I know the following code has a complexity of O(log(n)):
while (n>1)
{
counter++;
n/=2;
}
I understand that here, n is being divided in half on each iteration, meaning that if n was 1000 then it will take ten rounds to get out of the loop. How did this lead to O(log(n))?
Sorry for the simple question, I really tried my best to get it before I asked.
Each time through the loop, you divide by 2 (roughly; this will ignore rounding since it is an asymptotic argument). So if n = N at the start, after k iterations, n=N/(2^k). To arrive at n = 1, you have to satisfy 2^k = N. That is, k = log(N).