Search code examples
time-complexitybig-ologarithm

Why is code like i=i*2 considered O(logN) when in a loop?


Why because of the i=i*2 is the runtime of the loop below considered O(logN)?

for (int i = 1; i <= N;) {
  code with O(1);
  i = i * 2;
}

Solution

  • Look at 1024 = 210. How many times do you have to double the number 1 to get 1024?

    Times    1   2   3   4    5    6    7    8     9      10
    Result   2   4   8   16   32   64  128  256   512    1024
    

    So you would have to run your doubling loop ten times to get 210 And in general, you have to run your doubling loop n times to get 2n. But what is n? It's the log2 2n, so in general if n is some power of 2, the loop has to run log2n times to reach it.