14

Please consider the following triple-nested loop:

for (int i = 1; i <= n; ++i)
    for (int j = i; j <= n; ++j)
        for (int k = j; k <= n; ++k)
            // statement

The statement here is executed exactly $n(n+1)(n+2)\over6$ times. Could someone please explain how this formula was obtained? Thank you.

Kaveh
  • 22,661
  • 4
  • 53
  • 113
Xin
  • 141
  • 1
  • 1
  • 3

2 Answers2

14

You can count the number of times the innermost for loop is executed by counting the number of triplets $(i,j,k)$ for which it is executed.

By the loop conditions we know that: $1 \leq i \leq j \leq k \leq n$ . We can reduce it to the following simple combinatorics problem.

  • Imagine $n+2$ boxes of red colour placed in an array from left to right.
  • Pick any 3 boxes from the $n+2$ boxes and paint them blue.
  • Form a triplet $(i,j,k)$ as follows:
    • $i$ = 1 + number of red coloured boxes to the left of first blue box.
    • $j$ = 1 + number of red coloured boxes to the left of second blue box.
    • $k$ = 1 + number of red coloured boxes to the left of third blue box.

So, we just need to count the number of ways of picking 3 boxes from $n+2$ boxes which is $n+2 \choose 3$.

Juho
  • 22,905
  • 7
  • 63
  • 117
rizwanhudda
  • 549
  • 2
  • 9
3

for me, it's easier to notice the inner loop is executed $n-i$ times and the total number of executions in the inner loop is

$(n-i)+(n-i-1)+(n-i-2)+\ldots+1$

this can be rewritten as $\sum_{j=0}^{n-i} n-i-j$ and is executed $n$ times, so the total number of executions is

$$ \sum_{i=0}^{n}\sum_{j=0}^{n-i} n-i-j=\frac{n(n+1)(n+2)}{6} $$

andy mcevoy
  • 213
  • 1
  • 5