0

I am trying to determine the frequency count of a triple nested loop.

for i = 1 to n do
    for j = 1 to i do
        for k = i to j do
            x =  x + 1

I know that the statement x = x + 1 will not get executed until i attains the value of n

Any tips/suggestions on how to get started?

Tarang Hirani
  • 560
  • 1
  • 12
  • 43
  • This question would be a better fit on http://math.stackexchange.com . – David Eisenstat Aug 28 '14 at 03:15
  • "x = x + 1 will not get executed until i attains the value of n" is not really true. It will get executed when i=1 and j=1 and k=1. And then again when i=1 and j=1 and k=2 and on and on.... – jch Aug 28 '14 at 03:16
  • For every `i`, `x=x+1` get executed `r(r+1)/2` times where `r = absolute(1-i)+1` – hk6279 Aug 28 '14 at 03:40
  • 1
    Is this the correct code? We have the inequality `j <= i`, so it's odd that the start and stop for `k` are in the other order. – David Eisenstat Aug 28 '14 at 04:22

1 Answers1

1

Let's take 4 and 5 as examples. When i = 4,

...
    for j = 1 to 4 do
        for k = 4 to j do
            x =  x + 1

...j = 1
   for k = 4 to 1 do  // 4 times
       x =  x + 1
...j = 2
   for k = 4 to 2 do  // 3 times
       x =  x + 1
...j = 3
   for k = 4 to 3 do   // twice
       x =  x + 1
...j = 4
   for k = 4 to 4 do   // once
       x =  x + 1

When i = 5,

...
    for j = 1 to 5 do
        for k = 5 to j do
            x =  x + 1

...j = 1
   for k = 5 to 1 do  // 5 times
       x =  x + 1
...j = 2
   for k = 5 to 2 do  // 4 times
       x =  x + 1
...j = 3
   for k = 5 to 3 do   // 3 times
       x =  x + 1
...j = 4
   for k = 5 to 4 do   // twice
       x =  x + 1
...j = 5
   for k = 5 to 5 do   // once
       x =  x + 1

pattern?

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61