# What is the asymptotic complexity of the following code snippet?

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.

New contributor
johanso is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• 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$. – Apass.Jack Feb 12 at 2:00

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}})$$.