Let $n$ be given an natural number. We want to find the number of squares which have corners with integer coordinates between $0$ and $n$.
For example $n=1$, there is only one square; $n=2$ there are $6$ squares, for $n=3$ there are $20$ squares (we can rotate such squares using diagonals for example).
For $n=2$, the coordinates of squares`corners are :
(0, 0), (0, 1), (1, 1), (1, 0)
(0, 1), (0, 2), (1, 2), (1, 1)
(1, 0), (1, 1), (2, 1), (2, 0)
(1, 1), (1, 2), (2, 2), (2, 1)
(0, 0), (0, 2), (2, 2), (2, 0)
(0, 1), (1, 2), (2, 1), (1, 0)
So how to discover the formula for generally $n$ ?
You can look at how much space a square takes. I do not mean the area of the square. For example, with $n = 2$ the diagonal square and the $2 \times 2$ square both take $2 \times 2$ space.
If a square takes $k \times k$ space, then you can place it at $(n+1-k)^2$ different positions.
Now how many squares take $k \times k$ space? The answer is $k$. You can make some drawings to verify this.
Now we can sum over all those $k$. I let Mathematica simplify the expression to a polynomial. $$\sum_{k=1}^n k \cdot (n+1-k)^2 = \frac{1}{12}n^4+\frac{1}{3}n^3+\frac{5 }{12}n^2+\frac{1}{6}n$$
First 10 values are: 1, 6, 20, 50, 105, 196, 336, 540, 825, 1210
OEIS sequence: https://oeis.org/A002415 (moved by one such that f(3) = 6)