I'm new to Wolfram Mathematica and I want to calculate the expression of s (with respect to n) to get the same result as this python code.

s = 0
for i in [1..n]:  # iterate i from 1 to n
    for j in [1..n]:
        for k in [i..j]:  # When i > j, skip it.
            s += 1

For example, when n = 10, it should be $220$ in fact.

I tried this code in Mathematica:

Sum[1, {i, 1, n}, {j, 1, n}, {k, i, j}]

which tells me that the answer is $n^2$, not corresponding to my expectation.

I have found that Mathematica can deal with such summation whose upper bound is less than its lower bound correctly, when the bounds are constants (output $0$ as answer), but when there's a symbolic bound, the result will be something like this:

Sum[1, {i, j, k}]

1 - j + k

When $j > k + 1$, it comes with a negative value. I guess this is the reason for the previous wrong output.

I searched and learnt that I should set GenerateConditions to True for the expression with correct conditions. So I tried this code:

Sum[Sum[1, {k, i, j}, GenerateConditions -> True], {i, 1, n}, {j, 1, n}]

But I got this (copied from MMA online):

ConditionalExpression[Piecewise[{{1, n == 1}}, 0], n <= 1]

It doesn't tell what should be when $n > 1$. I'm really puzzled now, and I want to know how to handle this case properly or what the keywords I could search with?

  • 1
    $\begingroup$ The documentation is surprisingly unclear on the expected behaviour of Sum when the first limit is larger than the second $\endgroup$ – mikado Jan 1 '18 at 12:37

One way to do this is via Boole:

Sum[Boole[i <= k], {i, 1, n}, {j, 1, n}, {k, i, j}, Assumptions -> n \[Element] Integers]

...which produces: $$\begin{cases}\frac{1}{6} \left(n^3+3 n^2+2 n\right) & n\geq 1 \\0 & \text{True}\end{cases}$$

For $n=10$, this gives 220.

| improve this answer | |

No need for making it so complicated:

Sum[1, {j, 1, n}, {i, 1, j}, {k, i, j}]

1/6 n (1 + n) (2 + n)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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