patternMinor
Analyzing the time complexity of nested loops
Viewed 0 times
theloopsanalyzingtimenestedcomplexity
Problem
So I've been given a piece of pseudo code that involves nested loops. The answer to this question is Θ(n^5) but I do not understand why it is so.
What is the time complexity of this code?
The most inner loop, for k = 1 to j is Θ(j). Then the middle loop, for j = 1 to n^2 I thought, should produce Θ(n^2) as it loops from j = 1 to n^2 but I've been told it's Θ(n^4). I honestly do not understand how it could be Θ(n^4) when it's iterating from 1 to n^2. Can someone explain how this works in simple terms?
What is the time complexity of this code?
for i = 1 to n
for j = 1 to n*n
for k = 1 to j
Task
where the time complexity of Task is Θ(1)The most inner loop, for k = 1 to j is Θ(j). Then the middle loop, for j = 1 to n^2 I thought, should produce Θ(n^2) as it loops from j = 1 to n^2 but I've been told it's Θ(n^4). I honestly do not understand how it could be Θ(n^4) when it's iterating from 1 to n^2. Can someone explain how this works in simple terms?
Solution
Translating
$\qquad\displaystyle\begin{align*}
\#\mathrm{Task} \quad&= &&\sum_{i=1}^n \sum_{j=1}^{n^2} \sum_{k=1}^j 1 \\
&= && \sum_{i=1}^n \sum_{j=1}^{n^2} j \\
&= && \sum_{i=1}^n \frac{n^2(n^2 + 1)}{2} \\
&= && \frac{n^3(n^2 + 1)}{2}.
\end{align*}$
We use the closed form of the triangular numbers (which you find on any formulary if you have not memorized it). Finally, obtain a $\Theta$-class using standard tools.
for-loops into sums is the best way to approach this as the resulting calculations are elementary. We get:$\qquad\displaystyle\begin{align*}
\#\mathrm{Task} \quad&= &&\sum_{i=1}^n \sum_{j=1}^{n^2} \sum_{k=1}^j 1 \\
&= && \sum_{i=1}^n \sum_{j=1}^{n^2} j \\
&= && \sum_{i=1}^n \frac{n^2(n^2 + 1)}{2} \\
&= && \frac{n^3(n^2 + 1)}{2}.
\end{align*}$
We use the closed form of the triangular numbers (which you find on any formulary if you have not memorized it). Finally, obtain a $\Theta$-class using standard tools.
Context
StackExchange Computer Science Q#63670, answer score: 4
Revisions (0)
No revisions yet.