0

I am trying to understand the runtime complexity of the below code in terms of n.

I know that it is $Θ(n^{4/3})$, but I don't get why.

I thought the outer loop runs $log(n)$ times, the second one runs $n^{1/3}$ times and the innermost runs $O(log(n))$ times as it runs $i$ times and $i$ is at most $log(n)$. This would add up to $log^2(n)*n^{1/3}$, right?

for (int i = 1; i ≤ n; i = 2 ∗ i) {
    for (int j = 1; j∗j∗j ≤ n; j = j + 1) {
        for (int k = 1; k ≤ i∗i; k = k + i) {
            f();
        }
    }
}

( f() runs in constant time)

Thanks for any help!

  • The analysis leading to $\Theta (\log^2 n \cdot n^{\frac{1}{3}})$ looks right. So, the $\Theta (n^{\frac{4}{3}})$ claim looks wrong. – Gassa Jan 06 '19 at 16:13
  • Careful: the number if iterations of the inner-most loop depends on $i$. Translate the loops into sums (cf. our reference question) and simplify. (cc @Gassa -- that rough upper bound on the inner loop doesn't necessarily lead to that $\Theta$!) – Raphael Jan 06 '19 at 18:14
  • Hint: Factor out the sum over $j$; it's independent of the other two. Rewrite the rest as $\sum_{i=0}^{\log n} \sum_{k=0}^i \bigl[ (2^k - 1) \cdot 2^i + 1 \bigr]$ (add proper rounding to $\log n$). Why? Now simplify using standard formulae. – Raphael Jan 06 '19 at 18:25
  • Ow, thanks @Raphael! I see now the trap I've fallen into. Indeed, the innermost loop runs 1, 2, 4, 8, 16, ... times depending on i, instead of 1, 2, 3, 4, 5, ... times as I mistakenly thought. – Gassa Jan 06 '19 at 21:32

0 Answers0