Search⌘ K

Logarithmic Runtime

Explore the concept of logarithmic runtime and its impact on algorithm complexity. Understand how loops that multiply or divide by 2 run in O(log N) time. Analyze the harmonic series to grasp O(N log N) complexity, building a foundation for optimizing algorithms in competitive programming.

We'll cover the following...

Iterating powers of a number

Let’s analyze the loop below where we iterate over all powers of 22

for (int i = 1; i <= N; i *= 2)
    x++;
  • Iteration 11: i=1i=1
  • Iteration 22: i=2i=2
  • Iteration 33: i=4i=4
  • Iteration xx: i=2x1i=2^{x-1}

Let’s say the loop terminates after the jthj^{th} iteration, i.e.,

2j1<=N2^{j-1} <= N

j1<=logNj-1 <= logN

j<=logN+1j <= logN + 1

Hence, the loop runs (logN+1)(logN + 1) times.

In Big-O notation, the time complexity is O(logN)O(logN) ...