-2
for(int i = 0; i < N * N; i = i + 1)

    for(int j = 1; j < i + 1; j = j + 1)

        junk = junk + 1;

I need to determine the relationship between the number of < operations executed and N. I should give an exact answer, such as 27N + 18.

Any help is appreciated! Thanks

  • 1
    Have you made an attempt to solve the problem before consulting stackoverflow? Or can you elaborate on your problem that you `need` solved? – shafeen Oct 03 '15 at 19:48

1 Answers1

1

For the first loop, as you can see i starts from 0 and goes to N^2 -1

1) That means N^2 + 1 times.

For every i, inner loop starts with 1 goes to N^2

2) 1 + 2 + 3 ... (N^2) = N^2 * (N^2 +1 ) / 2 = (N^4 + N^2) / 2

That means, operator "<" executed sum of 1 and 2.

N^2 + 1 + (N^4 + N^2) / 2 = (N^4 + 3N^2 + 2) / 2

                      = **(N^2 + 2) (N^2 + 1) / 2**
Afsin Buyuksarac
  • 298
  • 1
  • 10
  • Why N^2 - 1 and not N^2 + 1? – Dale McCaughan Oct 03 '15 at 20:07
  • for(int j = 1; j < i + 1; j = j + 1) this loops start with 1 and goes to i (at most N^2-1 ), so total of 1+2+3....(N^2-1) – Afsin Buyuksarac Oct 03 '15 at 20:12
  • Also i forgot to mention that you have to account for the fact that getting out if a FOR loop requires a final test that fails. – Dale McCaughan Oct 03 '15 at 21:23
  • What does that mean ? – Afsin Buyuksarac Oct 03 '15 at 21:29
  • There will be an extra n^2 – Dale McCaughan Oct 03 '15 at 21:32
  • I see your point, conditions which are not satisfied for loops you said. Then for i , N^2 + 1 and or j as you said N^2. – Afsin Buyuksarac Oct 03 '15 at 21:36
  • I have numerous concerns about your solution. Firstly, I don't get your claim that the loop goes N^2+1 times. There are only N^2 integers from 0 to N^2-1 inclusive, so the loop runs N^2 times. Also, there's a single comparison for each `i` in the outer loop header and `i` comparisons for each `i` in the inner loop header. So, the total number of comparisons should be, $$\sum_{i=0}^{N^2-1} (1+i) = N^2 + (N^2*(N^2+1))/2 = N^2*(N^2+3)/2 $$ – learner Dec 31 '15 at 09:17