0

I have two interesting programs

And I just couldn't figure out the time complexity.

The first one:

for(i = 0; i < N; i++)
        for(j = 0; j < i * i; j++)
            for(k = 0; k < j; k ++)
                sum ++;
for(i = 1; i < N; i++)
    for(j = 1; j < i * i; j++) 
            if(j %i == 0)
            for(k = 0; k < j; k++)

These two have been troubling me for hours. My answer for the first one is O(n^5), and the second one is O(n^3). I don't know if I am correct.

Update: The answer to the second question is linked at the top of this page. Here is the solution to the first one: Computation Process

  • Can you show your working? Note that for these sorts of problems, it's quite feasible to calculate the result of `sum` at the end of a run - you just need to express the program as some sums... for example the first one is sum(sum(j, j=0..i*i-1), i=0..N-1). Wolfram alpha can give a closed-form expression for these, or you can use standard formulae for sums like (sum i, i=1..N), (sum i^2, i=1..N) and so on. – Paul Hankin Oct 21 '22 at 06:08
  • In the second, you can rewrite the inner loop to avoid the `j%i=0` test: `for (j = i; j < i * i; j += i) for (k=0; k < j; k++) sum++;`. This makes it much easier to calculate the runtime (assuming runtime is the number of times `sum` is incremented). – Paul Hankin Oct 21 '22 at 06:09
  • Here's wolfram alpha's solution for the first one -- and yes, it's Theta(N^5): https://www.wolframalpha.com/input?i=sum%28sum%28j%2C+j%3D0..i%5E2-1%29%2C+i%3D0..N-1%29 – Paul Hankin Oct 21 '22 at 06:11
  • What's your reasoning for your solutions ? – Alois Christen Oct 21 '22 at 06:17
  • Whoa, thank you so much. let me ponder for a while. this is really helpful! – 我从上边来 Oct 21 '22 at 06:18
  • The first one is straightforward, the second one is an exact duplicate of [this question](https://stackoverflow.com/q/60163597/12299000). – kaya3 Oct 21 '22 at 06:19
  • thx for your answer! but I didn't mean to make a duplicate of that question... – 我从上边来 Oct 21 '22 at 06:25
  • 1
    No worries, and it being a duplicate doesn't mean you've done anything wrong; it's not easy to find questions about this by searching. (I was only able to find the duplicate because I remember answering it.) I only emphasise that it's an exact duplicate because it means you don't have to adapt the answer to your question, the answer directly applies. – kaya3 Oct 21 '22 at 06:26

0 Answers0