Is there some way that I can analytically calculate this sum and get a formula into which I plug $n$ and get the correct answer?
Is there an analytic way to calculate $\sum_{i=1}^n |\frac{n}{2}-i|$
114 Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail AtThere are 3 best solutions below
On
Hint: Split the sum $$\sum_{i=1}^n |n/2 - i| = \sum_{i=1}^{\lfloor n/2 \rfloor} (n/2 - i) + \sum_{i=\lfloor n/2 \rfloor +1}^n (i-n/2)$$ and use the well-known formula for $\sum_{i=j}^k i$.
The result is
$$n(\lfloor n/2 \rfloor+1)-(\lfloor n/2 \rfloor+1)^2+ \lfloor n/2 \rfloor+1/2-n-n(n+1)/2+(n+1)^2/2$$
On
Since there are already many nice solutions posted above, here's an "intuitive" solution with the help of a numerical example.
Even $n$
Consider the case for $n=2m=6\quad (\frac n2=m=3)$.
$$\begin{array}& i&&\; 1& \;2& \;3& \;4&\; 5&6\\ \hline\\ \frac n2-i &&\;2&\; 1& \;0& -1& -2& -3\\ \big\lvert \frac n2 -i \big\rvert &&\;\color{blue}2&\; \color{blue}1& \;\color{red}0& \; \color{red}1& \; \color{green}2& \;\color{green}3\\ \hline \end{array}$$ Now sum by taking numbers in pairs, starting from the centre pair, and then alternating between the left and right pairs. $$\sum_{i=1}^n \big\lvert \frac n2 -i \big\rvert\; \Big \rvert_{n=6}=\color{red}{(0+1)}+\color{blue}{(1+2)}+\color{green}{(2+3)}=1+3+5=9=\left(\frac 62\right)^2$$ i.e. $$\sum_{i=1}^n \big\lvert \frac n2 -i \big\rvert=\sum_{i=1}^{2m}\big\lvert m -i \big\vert=\sum_{r=1}^m (2r-1)=m^2=\frac {n^2}4\qquad\blacksquare$$
Odd $n$
Consider the case for $n=2m+1=7\quad$ ($\frac n2=m+\frac 12$ or $m=\frac {n-1}2$) .
Using the same approach as before, then subtracting $\frac 12$ from each term (there are $7\; (=2m+1)$ terms), gives the same sum as above i.e. $9 \;(=m^2)$.
$$\begin{array}& i&&\; 1& \;2& \;3& \;4&\; 5&6 &\; 7\\ \hline\\ \frac n2-i &&2.5 &1.5 & 0.5 &-0.5 &-1.5& -2.5& -3.5\\ \big\lvert \frac n2 -i \big\rvert &&2.5 &1.5 & 0.5 &0.5 &1.5& 2.5& 3.5\\ \big\lvert \frac n2 -i \big\rvert-\frac 12 &&2&1 & 0 &0 &1& 2& 3\\ \\ \hline \end{array}$$
Hence the original sum is $9+7\cdot \frac 12=m^2+\frac {2m+1}2$, i.e.
$$\sum_{i=1}^n \big\lvert \frac n2 -i \big\rvert=\sum_{i=1}^{2m+1}\big\lvert \frac {n-1}2 -i \big\rvert =m^2+\frac {2m+1}2=\left(\frac {n-1}2\right)^2+\frac n2 =\frac {n^2+1}4\qquad\blacksquare$$
For even $n=2k$ this sum is $$\sum_{i=1}^k (k-i) + \sum_{i=k+1}^{2k} (i-k) = \sum_{i=1}^k k - \sum_{i=1}^ki + \sum_{j=1}^k j = k^2 = \frac{n^2}{4}$$ where $j=i-k$.
For odd $n=2k+1$, this sum is $$\sum_{i=1}^k \left(k+ \frac 12 -i \right) + \sum_{i=k+1}^{2k+1} \left(i-k- \frac 12 \right) =$$ $$= \sum_{i=1}^k \frac 12 + \sum_{i=1}^k k - \sum_{i=1}^k i + \sum_{i=j}^{k+1} j - \sum_{i=j}^{k+1} \frac 12 = k^2 +k + \frac{1}{2} = \frac{n^2+1}{4}$$
Putting everything together, the final formula is $$\sum_{i=1}^n \left| \frac{n}{2} - i \right| =\frac{n^2 + (n \mod{2})}{4}$$