How many squares in the $m \times n$ grid
Suppose $n\ge m$.
- Number of squares of size 1: $m\cdot n$
- Number of squares of size 2: $(m-1)\cdot (n-1)$
- ...
- Number of squares of size m: $1\cdot (n-m+1)$
Result: $$\begin{align} \sum_{k=1}^m k \cdot (n-m+k) & =(n-m)\sum_{k=1}^m k +\sum_{k=1}^m k^2 \\ & = (n-m) m(m+1)/2 + m(m+1)(2m+1)/6 \\ & = \frac{m(m+1) (3n-m+1)}{6}\end{align}$$