Taking the square of a finite series I was reading something that involved taking the square of a sum $\sum_{i=1}^k(n_i-1)$. The author just presented the result.
$$\left(\sum_{i=1}^k(n_i-1)\right)^2 = \sum_{i=1}^k(n_i^2-2n_i)+k + cross terms$$
Can someone clearly explain how the author arrived at the right-hand side of the equation. I'm not very good at manipulating sums mainly because I haven't done analysis. I've been checking other questions on this forum and noticed:
$$\left(\sum^n_{i=1}Z_i\right)^2 = \sum^n_{i=1}Z^2_i + \sum^n_{j \neq i}Z_iZ_j$$
By just doing some substitution I can see that the two equations look to be of the same type. However, I have no idea how it was derived. The guy provided the following but I did not understand the second and the third steps.
$$\begin{array}{ccl}
\left(\sum\limits_{j=0}^{n-1}Z_j\right)^2&=&\left(\sum\limits_{i=0}^{n-1}Z_i\right)\left(\sum\limits_{j=0}^{n-1}Z_j\right)\\
&=&\sum\limits_{j=0}^{n-1}Z_j\left(Z_j+\sum\limits_{j\neq i}Z_i\right)\\
&=&\sum\limits_{j=0}^{n-1}Z_j^2+\sum\limits_{j\neq i}Z_iZ_j\\
\end{array}$$
Again, if possible, can someone refer help derive it or refer me to a book/site where I can get comfortable with these types of identities.
Thanks
 A: So, if we have a sum in the form $S_a=\sum_{n=1}^N a_n$ and another sum in the form $T_b=\sum_{m=1}^N b_m$ the product of $S_a$ and $T_b$ is given by 
$$S_aT_b=\left(\sum_{n=1}^N a_n\right)\left(\sum_{m=1}^N b_m\right)=\sum_{n=1}^N \sum_{m=1}^Na_n b_m$$
Now, the products of terms of the same index can be written as 
$$\sum_{n=1}^N a_n b_n$$
from which we can write
$$\begin{align}
S_aT_b&=\left(\sum_{n=1}^N \sum_{m=1}^Na_n b_m-\sum_{n=1}^N a_n b_n\right)+\sum_{n=1}^N a_n b_n\\
&=\sum_{n=1}^N a_n\left(\sum_{m=1}^N b_m- b_n\right)+\sum_{n=1}^N a_n b_n\\
&=\sum_{n=1}^N a_n\left(\sum_{m\ne n}^N b_m\right)+\sum_{n=1}^N a_n b_n\\
&=\sum_{n=1}^N\sum_{m\ne n}^N a_n b_m+\sum_{n=1}^N a_n b_n
\end{align}$$
In the first line, we simply added and subtracted the product of the same index.
In the second line, we used the distributive property and factored the sum, $\sum_{m=1}^N a_n$.
In the third line, we removed the $n^{\text{th}}$ term from the sum, $\sum_{m=1}^N b_m$.
In the fourth line, we used the distributive property again.
