I am exploring combinatorial methods to solve a problem related to counting the number of squares in a grid. Given an 'a x b' grid of evenly spaced points, I want to understand how to determine the total number of squares that can be formed in the grid. I solved the problem with programming with basic loops, but was wondering if there is a more elegant math solution.
First example: 15 squares with a length of 1
Second example: 8 squares with a length of 2
Third case: 3 squares with a length of 3
So in this case the grid is a = 4, b = 6, 4x6 grid and the sum of all squares would be 26.
I would appreciate any insights, explanations, or resources on combinatorial methods for counting squares in such grids.



In your example, the $3x5$ grid provided $3 \times 5$ squares of size 2, $2 \times 4$ squares of size 2, and $1 \times 3$ squares of size 2.
There's 2 key observations to make:
(1) Given the smaller dimension of the grid ($n=3$), we can create squares up to size $3$.
(2) Given the dimensions of the grid ($a \times b$), the number of squares of size $n$ can be determined by $(a-n+1) \times (b-n+1)$.
This means that given a $a \times b$ grid, we can calculate the total number of squares as $$\sum_{i=1}^n (a-i+1) \times (b-i+1)$$ where $n = \min(a,b)$.