# Count number of squares in a rectangle

Last Updated : 20 Sep, 2023

Given a m x n rectangle, how many squares are there in it?

Examples :

`Input:  m = 2, n = 2Output: 5There are 4 squares of size 1x1 + 1 square of size 2x2.Input: m = 4, n = 3Output: 20There are 12 squares of size 1x1 +           6 squares of size 2x2 +           2 squares of size 3x3.`

Recommended Practice

Let us first solve this problem for m = n, i.e., for a square:
For m = n = 1, output: 1
For m = n = 2, output: 4 + 1 [ 4 of size 1×1 + 1 of size 2×2 ]
For m = n = 3, output: 9 + 4 + 1 [ 9 of size 1×1 + 4 of size 2×2 + 1 of size 3×3 ]
For m = n = 4, output 16 + 9 + 4 + 1 [ 16 of size 1×1 + 9 of size 2×2 + 4 of size 3×3 + 1 of size 4×4 ]
In general, it seems to be n^2 + (n-1)^2 + … 1 = n(n+1)(2n+1)/6

Let us solve this problem when m may not be equal to n:
Let us assume that m <= n

From above explanation, we know that number of squares in a m x m matrix is m(m+1)(2m+1)/6

What happens when we add a column, i.e., what is the number of squares in m x (m+1) matrix?

When we add a column, number of squares increased is m + (m-1) + … + 3 + 2 + 1
[ m squares of size 1×1 + (m-1) squares of size 2×2 + … + 1 square of size m x m ]
Which is equal to m(m+1)/2

So when we add (n-m) columns, total number of squares increased is (n-m)*m(m+1)/2.
So total number of squares is m(m+1)(2m+1)/6 + (n-m)*m(m+1)/2.
Using same logic we can prove when n <= m.

So, in general,

`Total number of squares = m x (m+1) x (2m+1)/6 + (n-m) x m x (m+1)/2 when n is larger dimension`

Using above logic for rectangle, we can also prove that number of squares in a square is n(n+1)(2n+1)/6

Below is the implementation of above formula.

## C++

 `// C++ program to count squares ` `// in a rectangle of size m x n` `#include` `using` `namespace` `std;`   `// Returns count of all squares ` `// in a rectangle of size m x n` `int` `countSquares(``int` `m, ``int` `n)` `{` `// If n is smaller, swap m and n` `if` `(n < m)` `    ``swap(m, n);`   `// Now n is greater dimension, ` `// apply formula` `return` `m * (m + 1) * (2 * m + 1) / ` `     ``6 + (n - m) * m *(m + 1) / 2;` `}`   `// Driver Code` `int` `main()` `{` `int` `m = 4, n = 3;` `cout << ``"Count of squares is "` `     ``<< countSquares(m, n);` `}`

## C

 `// C program to count squares ` `// in a rectangle of size m x n`   `#include `   `// Returns count of all squares ` `// in a rectangle of size m x n` `int` `countSquares(``int` `m, ``int` `n)` `{` `  ``int` `temp;` `// If n is smaller, swap m and n` `  ``if` `(n < m)` `  ``{` `      ``temp=n;` `      ``n=m;` `      ``m=temp;` `  ``}` `  ``// Now n is greater dimension, ` `  ``// apply formula` `  ``return` `m * (m + 1) * (2 * m + 1) / ` `      ``6 + (n - m) * m *(m + 1)/ 2;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `m = 4, n = 3;` `    ``printf``(``"Count of squares is %d"``,countSquares(m, n));` `}`   `// This code is contributed by Hemant Jain.`

## Java

 `// Java program to count squares` `// in a rectangle of size m x n`   `class` `GFG` `{` `    ``// Returns count of all squares ` `    ``// in a rectangle of size m x n` `    ``static` `int` `countSquares(``int` `m, ``int` `n)` `    ``{` `    ``// If n is smaller, swap m and n` `    ``if` `(n < m)` `    ``{` `        ``// swap(m, n)` `        ``int` `temp = m;` `        ``m = n;` `        ``n = temp;` `    ``}` `        `  `    `  `    ``// Now n is greater dimension, ` `    ``// apply formula` `    ``return` `m * (m + ``1``) * (``2` `* m + ``1``) / ` `        ``6` `+ (n - m) * m * (m + ``1``) / ``2``;` `    ``}` `    `  `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) ` `    ``{` `        ``int` `m = ``4``, n = ``3``;` `        ``System.out.println(``"Count of squares is "` `+ ` `                            ``countSquares(m, n));` `    ``}` `}`

## Python3

 `# Python3 program to count squares` `# in a rectangle of size m x n`   `# Returns count of all squares ` `# in a rectangle of size m x n` `def` `countSquares(m, n):` `    `  `    ``# If n is smaller, swap m and n` `    ``if``(n < m):` `        ``temp ``=` `m` `        ``m ``=` `n` `        ``n ``=` `temp` `        `  `    ``# Now n is greater dimension, ` `    ``# apply formula` `    ``return` `((m ``*` `(m ``+` `1``) ``*` `(``2` `*` `m ``+` `1``) ``/` `           ``6` `+` `(n ``-` `m) ``*` `m ``*` `(m ``+` `1``) ``/` `2``))`   `# Driver Code` `if` `__name__``=``=``'__main__'``:` `    ``m ``=` `4` `    ``n ``=` `3` `    ``print``(``"Count of squares is "` `         ``,countSquares(m, n))`   `# This code is contributed by mits.`

## C#

 `// C# program to count squares in a rectangle` `// of size m x n` `using` `System;`   `class` `GFG {` `    `  `    ``// Returns count of all squares in a ` `    ``// rectangle of size m x n` `    ``static` `int` `countSquares(``int` `m, ``int` `n)` `    ``{` `    ``// If n is smaller, swap m and n` `    ``if` `(n < m)` `    ``{` `        ``// swap(m,n)` `        ``int` `temp = m;` `        ``m = n;` `        ``n = temp;` `    ``}` `            `  `    ``// Now n is greater dimension, apply ` `    ``// formula` `    ``return` `m * (m + 1) * (2 * m + 1) / 6 + ` `               ``(n - m) * m * (m + 1) / 2;` `    ``}` `    `  `    ``// Driver method` `    ``public` `static` `void` `Main() ` `    ``{` `        ``int` `m = 4, n = 3;` `        `  `        ``Console.WriteLine(``"Count of squares is "` `                          ``+ countSquares(m, n));` `    ``}` `}`   `//This code is contributed by vt_m.`

## Javascript

 ``

## PHP

 ``

Output :

`Count of Squares is 20`

Time complexity: O(1)

Auxiliary Space: O(1)

Alternate Solution :

1. Let us take m = 2, n = 3;
2. The number of squares of side 1 will be 6 as there will be two cases one as squares of 1-unit sides along with the horizontal(2) and the second case as squares of 1-unit sides along the vertical(3). that give us 2*3 = 6 squares.
3. When the side is 2 units, one case will be as squares of the side of 2 units along only one place horizontally and the second case as two places vertically. So, the number of squares=2
4. So we can deduce that, Number of squares of size 1*1 will be m*n. The number of squares of size 2*2 will be (n-1)(m-1). So like this, the number of squares of size n will be 1*(m-n+1).

The final formula for the total number of squares will be n*(n+1)(3m-n+1)/6 .

## C++

 `// C++ program to count squares` `// in a rectangle of size m x n` `#include ` `using` `namespace` `std;`   `// Returns count of all squares` `// in a rectangle of size m x n` `int` `countSquares(``int` `m, ``int` `n)` `{`   `    ``// If n is smaller, swap m and n` `    ``if` `(n < m) {` `        ``int` `temp = m;` `        ``m = n;` `        ``n = temp;` `    ``}`   `    ``// Now n is greater dimension,` `    ``// apply formula` `    ``return` `n * (n + 1) * (3 * m - n + 1) / 6;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `m = 4, n = 3;` `    ``cout << ``"Count of squares is "` `<< countSquares(m, n);` `}`   `// This code is contributed by 29AjayKumar`

## C

 `// C program to count squares ` `// in a rectangle of size m x n`   `#include `   `// Returns count of all squares` `// in a rectangle of size m x n` `int` `countSquares(``int` `m, ``int` `n) ` `{`   `    ``// If n is smaller, swap m and n` `    ``if` `(n < m) ` `    ``{` `        ``int` `temp = m;` `        ``m = n;` `        ``n = temp;` `    ``}`   `    ``// Now n is greater dimension,` `    ``// apply formula` `    ``return` `n * (n + 1) * (3 * m - n + 1) / 6;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `m = 4, n = 3;` `    ``printf``(``"Count of squares is %d"``,countSquares(m, n));` `}`   `// This code is contributed by Hemant Jain`

## Java

 `// Java program to count squares ` `// in a rectangle of size m x n ` `import` `java.util.*;`   `class` `GFG ` `{`   `    ``// Returns count of all squares` `    ``// in a rectangle of size m x n` `    ``static` `int` `countSquares(``int` `m, ``int` `n) ` `    ``{`   `        ``// If n is smaller, swap m and n` `        ``if` `(n < m) ` `        ``{` `            ``int` `temp = m;` `            ``m = n;` `            ``n = temp;` `        ``}`   `        ``// Now n is greater dimension,` `        ``// apply formula` `        ``return` `n * (n + ``1``) * (``3` `* m - n + ``1``) / ``6``;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) ` `    ``{` `        ``int` `m = ``4``;` `        ``int` `n = ``3``;` `        ``System.out.print(``"Count of squares is "` `+ ` `                             ``countSquares(m, n));` `    ``}` `}`   `// This code is contributed by 29AjayKumar`

## Python3

 `# Python3 program to count squares ` `# in a rectangle of size m x n `   `# Returns count of all squares ` `# in a rectangle of size m x n ` `def` `countSquares(m, n): ` `    `  `    ``# If n is smaller, swap m and n ` `    ``if``(n < m): ` `        ``temp ``=` `m ` `        ``m ``=` `n ` `        ``n ``=` `temp ` `        `  `    ``# Now n is greater dimension, ` `    ``# apply formula ` `    ``return` `n ``*` `(n ``+` `1``) ``*` `(``3` `*` `m ``-` `n ``+` `1``) ``/``/` `6`   `# Driver Code ` `if` `__name__``=``=``'__main__'``: ` `    ``m ``=` `4` `    ``n ``=` `3` `    ``print``(``"Count of squares is"``,` `           ``countSquares(m, n)) `   `# This code is contributed by AnkitRai01 `

## C#

 `// C# program to count squares ` `// in a rectangle of size m x n ` `using` `System;`   `class` `GFG ` `{`   `    ``// Returns count of all squares` `    ``// in a rectangle of size m x n` `    ``static` `int` `countSquares(``int` `m, ``int` `n) ` `    ``{`   `        ``// If n is smaller, swap m and n` `        ``if` `(n < m) ` `        ``{` `            ``int` `temp = m;` `            ``m = n;` `            ``n = temp;` `        ``}`   `        ``// Now n is greater dimension,` `        ``// apply formula` `        ``return` `n * (n + 1) * (3 * m - n + 1) / 6;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(String[] args) ` `    ``{` `        ``int` `m = 4;` `        ``int` `n = 3;` `        ``Console.Write(``"Count of squares is "` `+ ` `                          ``countSquares(m, n));` `    ``}` `}`   `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output :

`Count of Squares is 20`

Time complexity: O(1)

Auxiliary Space: O(1)

Thanks to Pranav for providing this alternate solution.

#### Approach#3: Using loop

This approach counts the number of squares in a given rectangle of size m x n by iterating over all possible square sizes from 1 to the minimum of m and n, and adding up the number of squares of each size that can fit in the rectangle.

#### Algorithm

1. Initialize a counter variable to 0.
2. Iterate over all possible square sizes, i.e. from 1 to min(m, n).
3. For each square size, calculate the number of squares that can be formed.
4. Add this count to the counter variable.
5. Return the final count.

## C++

 `#include ` `using` `namespace` `std;`   `// Function to count the number of squares in an m x n grid` `int` `count_squares(``int` `m, ``int` `n) {` `    ``int` `count = 0;` `    ``for` `(``int` `i = 1; i <= min(m, n); i++) {` `        ``// Calculate the number of squares ` `        ``//with side length 'i' that fit in the grid` `        ``count += (m - i + 1) * (n - i + 1);` `    ``}` `    ``return` `count;` `}`   `int` `main() {` `    ``int` `m = 4;` `    ``int` `n = 3;` `    ``cout << count_squares(m, n) << endl;` `    ``return` `0;` `}`

## Java

 `public` `class` `Main {` `    ``public` `static` `void` `main(String[] args) {` `        ``int` `m = ``4``;` `        ``int` `n = ``3``;` `        ``System.out.println(countSquares(m, n));` `    ``}`   `    ``// Function to count the number of squares in an m x n grid` `    ``public` `static` `int` `countSquares(``int` `m, ``int` `n) {` `        ``int` `count = ``0``;` `        ``for` `(``int` `i = ``1``; i <= Math.min(m, n); i++) {` `            ``// Calculate the number of squares with` `            ``// side length 'i' that fit in the grid` `            ``count += (m - i + ``1``) * (n - i + ``1``);` `        ``}` `        ``return` `count;` `    ``}` `}`

## Python3

 `# Function to count the number of squares in an m x n grid` `def` `count_squares(m, n):` `    ``count ``=` `0` `    ``for` `i ``in` `range``(``1``, ``min``(m, n) ``+` `1``):` `        ``# Calculate the number of squares ` `        ``# with side length 'i' that fit in the grid` `        ``count ``+``=` `(m ``-` `i ``+` `1``) ``*` `(n ``-` `i ``+` `1``)` `    ``return` `count`   `m ``=` `4` `n ``=` `3` `print``(count_squares(m, n))`

## C#

 `using` `System;`   `public` `class` `CountSquaresInGrid` `{` `    ``public` `static` `int` `CountSquares(``int` `m, ``int` `n)` `    ``{` `        ``int` `count = 0;` `        `  `        ``// Iterate through the side lengths of squares` `        ``// from 1 to the minimum of m and n.` `        ``for` `(``int` `i = 1; i <= Math.Min(m, n); i++)` `        ``{` `            ``// For each side length 'i', calculate` `            ``// the number of squares that can fit in the grid.` `            ``count += (m - i + 1) * (n - i + 1);` `        ``}` `        `  `        ``return` `count;` `    ``}`   `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``int` `m = 4;` `        ``int` `n = 3;` `        `  `        ``// Call the function to count squares in the grid and print the result.` `        ``int` `result = CountSquares(m, n);` `        ``Console.WriteLine(result);` `    ``}` `}`

## Javascript

 `// Function to count the number of squares in an m x n grid` `function` `count_squares(m, n) {` `    ``let count = 0;` `    ``// Iterate over all possible square sizes` `    ``for` `(let i = 1; i <= Math.min(m, n); i++) {` `        ``// Count the number of squares of size 'i' that can fit in the grid` `        ``count += (m - i + 1) * (n - i + 1);` `    ``}` `    ``return` `count;` `}`   `let m = 4;` `let n = 3;` `console.log(count_squares(m, n)); ``// Output: 20`

Output

```20

```

Time Complexity: O(m * n * min(m, n))
Space Complexity: O(1)