I was given the folllowing problem.
Give necessary and sufficient conditions for $$(A+B)^2 = A^2 +2AB + B^2$$ $$A^2 - B^2 = (A+B)(A-B)$$ to hold with $A, B \in \mathbb{K}^{n\times n}$.
I was wondering if there was a simpler way to find the conditions than the one I used. What I did was the following.
For $C:=(A+B)^2$ we have $c_{ij}=\sum_{k=1}^n (a_{ik}+b_{ik})(a_{kj} + b_{kj})$ For $X:=A^2, Y:=2AB, Z:=B^2$ we have
$$x_{ij}=\sum_{k=1}^n a_{ik}a_{kj}$$ $$y_{ij}=2\sum_{k=1}^n a_{ik}b_{kj}$$ $$z_{ij}=\sum_{k=1}^n b_{ik}b_{kj} $$
Then $(A+B)^2 = A^2+2AB+B^2 \iff c_{ij}= x_{ij}+y_{ij}+ z_{ij}$. This equation is equivalent to
\begin{align*} \sum_{k=1}^n (a_{ik}+b_{ik})(a_{kj} + b_{kj}) &= \sum_{k=1}^n a_{ik}a_{kj} + 2\sum_{k=1}^n a_{ik}b_{kj} + \sum_{k=1}^n b_{ik}b_{kj} \end{align*}
Expanding the LHS we obtain
\begin{align*} \sum_{k=1}^n \Big(a_{ik}a_{kj}+a_{ik}b_{kj} + b_{ik}a_{kj}+b_{ik}b_{kj}\Big) \\ =\sum_{k=1}^n a_{ik}a_{kj}+\sum(a_{ik}b_{kj}+b_{ik}a_{kj})+\sum_{k=1}^n b_{ik}b_{kj} \end{align*}
and then the equation becomes
$$\sum_{k=1}^n a_{ik}a_{kj}+\sum(a_{ik}b_{kj}+b_{ik}a_{kj})+\sum_{k=1}^n b_{ik}b_{kj} = \sum_{k=1}^n a_{ik}a_{kj} + 2\sum_{k=1}^n a_{ik}b_{kj} + \sum_{k=1}^n b_{ik}b_{kj}$$
$$\sum_{k=1}^n (a_{ik}b_{kj}+b_{ik}a_{kj}) = 2\sum_{k=1}^n a_{ik}b_{kj}$$
$$a_{ik}b_{kj}=b_{ik}a_{kj}$$
Since $a_{ik}b_{kj}=b_{ik}a_{kj} \iff A \cdot B = B \cdot A$ the necessary and sufficient condition for $(A+B)^2=A^2+2AB+B^2$ is that $A \cdot B = B \cdot A$.
PD: Excuse the bad formatting. It seems the \\ break for making new lines is not working, at least in my computer, so for every new line I had to create a new equation environment (which made alignment impossible).
I think the answer they were looking for is that it is necessary and sufficient for $A$ and $B$ to commute, for both equations $A^2-B^2 = (A-B)(A+B)$ and $(A+B)=A^2+2AB+B^2$ to hold.
Note that
$$(A+B)^2 = (A+B)(A+B)$$ $$=A^2 + AB+BA + B^2.$$
Then for the equation $A^2+AB+BA+B^2 = A^2+2AB+B^2$ to hold, simple algebra implies that the equation $AB=BA$ must hold. It is easy to see that this is a sufficient condition as well.
Likewise,
$$(A+B)(A-B) = A^2-AB+BA-B^2,$$ and for $A^2-AB+BA-B^2 = A^2-B^2$ to hold, it follows from simple algebra that the equation $AB=BA$ must hold. It is easy to see that this is a sufficient condition as well.