1

I need to figure out the complexity of the following loop in theta notation but I can't figure it out. Some help would be much appreciated.

from j := 1 until j > n loop
  from k := 1 until k > n*n*n loop
     k := k + j
  end
j := j + 2
end

some help with an explanation would be much appreciated. The solutions state $\theta(n^3log(n))$. it is clear that the second loop executes $n^3$ times but where does the $log$ come from?

Thanks a lot in advance

Raphael
  • 72,336
  • 29
  • 179
  • 389
  • What have you tried so far? Check out this . See if you can write out how many times the inner loop will execute based on the outer loop (e.g. when $j=1$, the inner loop runs $x$ times, when $j=3$ the inner loop runs $x'$ times, etc.) then you might be able to find a pattern or summation. – ryan Aug 02 '17 at 20:25
  • That question, and others tagged [tag:algorithm-analysis+loops]. – Raphael Aug 02 '17 at 20:26
  • Please check your source code. It cannot be log. Maybe j := j / 2 ? – fade2black Aug 02 '17 at 21:49
  • @fade2black, it is $n^3 \log n$, the solution is correct. (Harmonic Number $H_n = \Theta(\log n)$) Write out the summation and you should see it. – ryan Aug 02 '17 at 22:23
  • @ryan The outer loop is the sum of odd numbers. The inner loop is always $n^3$. – fade2black Aug 02 '17 at 22:29
  • 1
    @fade2black $j$ is also affecting the inner loop. The summation would be $$ \begin{align} T(n) & = n^3 / 1 + n^3 / 3 + n^3 / 5 + \dots n^3 / n \ & = n^3 \cdot (1 + 1/3 + 1/5 + \dots + 1/n) \ &= n^3 \Theta( H_n) \ T(n) & = \Theta( n^3 \log n) \end{align}$$ – ryan Aug 02 '17 at 22:32
  • @ryan could u please send me the line in the inner loop? Is it k = k + 1? – fade2black Aug 02 '17 at 22:58
  • 1
    @fade2black it is "k = k + j" in the inner loop. – ryan Aug 02 '17 at 23:51
  • @ryan I don't quite understand why do you say (1 + 1/3 + 1/5 +... + 1/n)? why do you divide? Could you please explain? I get that the inner loop also depends on j and j is (1,3,5,7,.....), so in a way, we need to find out how fast k approaches $n^3$, but I don't follow the rest. Thanks – DariusTheGreat Aug 03 '17 at 06:46
  • 1
    @DariusTheGreat, the first time the inner loop is executed it increments by 1, then by 3, then by 5, then by let's say $x$. Each time it iterates to $n^3$, so we clearly take $n^3/x$ steps to get there. – ryan Aug 03 '17 at 06:59

0 Answers0