Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose we have the following:

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

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

In either case, is there a straightforward way to know how many times "statement" will be executed? Thank you.

share|cite|improve this question
up vote 5 down vote accepted

Yes. You are effectively computing

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

In this case there's an easy geometric way of visualizing the sum: you're counting the number of entries in a $n\times n$ matrix lying on or below the diagonal.


\begin{align*} \sum_{i=1}^n \sum_{j=i}^n \sum_{k=j}^n &= \sum_{i=1}^n \sum_{j=i}^n (n-j+1)\\ &= \sum_{i=1}^n\left[\sum_{j=i}^n(n+1) - \sum_{j=i}^nj\right]\\ &= \sum_{i=1}^n\left[(n-i+1)(n+1) - \sum_{j=i}^nj\right]\\ &= \sum_{i=1}^n\left[(n-i+1)(n+1) - \left(\sum_{j=1}^n j-\sum_{j=1}^{i-1}j\right)\right]\\ &=\sum_{i=1}^n\left[(n-i+1)(n+1) - \frac{n(n+1)}{2} + \frac{i(i-1)}{2}\right]\\ &= n(n+1)^2 - \frac{n^2(n+1)}{2} - \frac{n(n+1)^2}{2} - \frac{n(n+1)}{4} + \frac{n(n+1)(2n+1)}{12}\\ &=\frac{n(n^2+3n+2)}{6}. \end{align*}

share|cite|improve this answer
Can you elaborate on the steps in the triple summation? Namely, how we arrive at this: $= \sum_{i=1}^n\left[(n-i+1)(n+1) - \sum_{j=i}^nj\right]\\$ and this: $=\sum_{i=1}^n\left[(n-i+1)(n+1) - \frac{n(n+1)}{2} + \frac{i(i-1)}{2}\right]\\$ – Bob John Jan 16 '13 at 7:18
I've added some extra steps. – user7530 Jan 16 '13 at 7:38

more short answer would be C(n+2,3) + C(n+1,2) by fundamental principles of counting C(n+the number of loop-1,the number of loop)

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.