# Sum with conditions and iterations

I need to use Sum in a unique way. Say we have a number $$N$$ passed in, I want to calculate and add all these series:

$$N^2$$

plus

$$1+2+\cdots+(N-1)+ \\ 1+2+\cdots+(N-2)+ \\ 1+2+\cdots+(N-3)+ \\ \vdots \\ +1$$

plus $$1+2+\cdots+(N-3)+ \\ 1+2+\cdots+(N-5)+\\ 1+2+\cdots+(N-7)+\\ \vdots \\ +1$$ In such a fashion so that those series stay positive always! For example if $$N=8$$, then both those go until the $$(N-7)$$ which is literally $$1$$ (the last terms).
If $$N=1$$, both series will not exist (as middle one will be $$0=N-1$$ and last one will be $$-2=N-3$$) etc.

I want to represent this with one nice Sum with those conditions. Then I assume we can FullSimplify it!

It looks like you are looking for the following expression:

$$S = n^2 + \sum _{k=1}^{n-1} \sum _{i=1}^{n-k} i + \sum _{k=1}^{\left\lfloor \frac{n-2}{2}\right\rfloor } \sum _{i=0}^{n-(2 k+1)} i,$$

which can be evaluated to:

$$S = \frac{1}{6} \left(\left\lfloor \frac{n}{2}\right\rfloor \left(\left\lfloor \frac{n}{2}\right\rfloor \left(4 \left\lfloor \frac{n}{2}\right\rfloor -6 n-3\right)+3 n (n+1)-1\right)+n (n+1) (n+2)\right),$$

or more elegantly written as:

$$S = \begin{cases} \frac{1}{6} \left(n^3-n\right)+n^2+\frac{1}{24} \left(2 n^3-9 n^2+10 n\right) & n \text{ is even,} \\ \frac{1}{6} \left(n^3-n\right)+n^2+\frac{1}{24} \left(2 n^3-9 n^2+10 n-3\right) & n \text{ is odd.} \\ \end{cases}$$

s = n^2 + Sum[i, {k, 1, n - 1}, {i, 1, n - k}] +
Sum[i, {k, 1, Floor[(n - 2)/2]}, {i, 0, n - (2*k + 1)}];
Table[{n, s}, {n, 1, 10}] // Grid
(*
1     1
2     5
3     13
4     27
5     48
6     78
7     118
8     170
9     235
10    315
*)

• +1 Looking up the results in oeis.org finds sequence A002717: Floor[n(n+2)(2n+1)/8].
– JimB
Commented Jul 23 at 13:29
• Thanks @Domen, amazing aggregation into a simple series! Bravo.... Results look accurate. Can it be Simplified by Mathematica to output the equations which you gave at the end? Commented Jul 23 at 14:56
• @Steve237, I don't know whether there is a way to simplify Floor by assuming even or odd $n$ ... So I just manually replaced Floor[(n - 2)/2] with (n - 2)/2 for even and (n - 3)/2 for odd $n$. Commented Jul 23 at 15:02
• Thanks, i mean the one with ODD and EVEN at the end...can Mathematica derive thsoe 2 equations? Commented Jul 23 at 15:10
• Yes, as I said, just replace Floor[(n - 2)/2] in s with either of the two terms I mentioned. Mathematica will then give you the two expressions. Commented Jul 23 at 15:21