Logarithmic Runtime
In this lesson, we'll discuss when an algorithm can have a logarithmic runtime.
We'll cover the following
Iterating powers of a number
Let’s analyze the loop below where we iterate over all powers of
for (int i = 1; i <= N; i *= 2)
x++;
- Iteration :
- Iteration :
- Iteration :
- …
- Iteration :
Let’s say the loop terminates after the iteration, i.e.,
Hence, the loop runs times.
In Big-O notation, the time complexity is
A similar analysis gives runtime for the loop below.
for (int i = N; i >= 1; i /= 2)
x++;
Harmonic series
Consider the piece of code below:
for (int i = 1; i <= N; i++)
for (int j = i; j <= N; j += i)
x++;
For all integers between and , we iterate over their multiples. The number of operations, therefore, will be:
Let’s define an upper bound on the second term. Grouping the terms, we get:
First term:
Second term:
Third term:
and so on.
Let be the number of groups we can make, then
Coming back to the number of operations, we have
Therefore, the time complexity is
In the next lesson, we’ll discuss an example where the runtime is not what it seems at a first glance.
Get hands-on with 1400+ tech skills courses.