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?
Sum
when the first limit is larger than the second $\endgroup$