0
$\begingroup$
for (i = 2; i < n; i = i * i) {
  for (j = 1; j < i / 2; j = j + 1) {
    sum = sum + 1;
  }
}

I know that the outer loop can run for a maximum of $n^2$ times and the inner loop will run for $\frac{n^2}{4}$ times.

$\endgroup$
  • 1
    $\begingroup$ Have you run your code for a few times? Can you print out sum at the end of the code? The printout will be the number of times the inner loop has been executed. Check whether it is expected, for example, when you set $n=10^6$. $\endgroup$ – Apass.Jack Feb 12 at 2:00
0
$\begingroup$

The second loop runs in $O(i)$. The first loop goes over the powers $2^{2^0}, 2^{2^1}, 2^{2^2}, \ldots$, until reaching $n$. So the overall running time is $$ O(2^{2^0} + 2^{2^1} + 2^{2^2} + \cdots + 2^{2^m}), $$ where $m$ is the maximal integer such that $2^{2^m} < n$. We can bound $$ 2^{2^0} + 2^{2^1} + 2^{2^2} + \cdots + 2^{2^m} \leq 2^1 + 2^2 + 2^3 + \cdots + 2^{2^m} \leq 2^{2^m+1} < 2n. $$ Therefore the overall running time is $O(n)$.

In fact, the same analysis gives the optimal bound $\Theta(2^{2^{\lfloor \log_2 \log_2 (n-1) \rfloor}})$.

$\endgroup$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.