It's actually easier to do this algebraically, using n rather than 40. So suppose that the vertices are at the points (i,j) with 0 ≤ i,j ≤ n. Now count the number of possible squares according to the length of their sides.

For squares of side 1, the lower left corner of the square can be at any point (i,j) with 0 ≤ i,j ≤ n–1. So there are such squares.

For squares of side 2, the lower left corner of the square can be at any point (i,j) with 0 ≤ i,j ≤ n–2. So there are such squares.

...

For squares of side n, the lower left corner of the square can can only be at the point (0,0). So there is only 1 such square.

Now you take it from there ... .

[The big advantage of using n rather than 40 is that you can check whether your answer is likely to be correct, by seeing what it tells you for some small value of n, like n=3 say. In that case, you can actually count the number of possible squares and check whether that agrees with the answer given by your formula.]