We are given a N*M grid, print the number of rectangles in it.
Input : N = 2, M = 2 Output : 9 There are 4 rectangles of size 1 x 1. There are 2 rectangles of size 1 x 2 There are 2 rectangles of size 2 x 1 There is one rectangle of size 1 x 1. Input : N = 5, M = 4 Output : 150 Input : N = 4, M = 3 Output: 60
We have discussed counting number of squares in a n x m grid,
Let us derive a formula for number of rectangles.
If the grid is 1×1, there is 1 rectangle.
If the grid is 2×1, there will be 2 + 1 = 3 rectangles
If it grid is 3×1, there will be 3 + 2 + 1 = 6 rectangles.
we can say that for N*1 there will be N + (N-1) + (n-2) … + 1 = (N)(N+1)/2 rectangles
If we add one more column to N×1, firstly we will have as many rectangles in the 2nd column as the first,
and then we have that same number of 2×M rectangles.
So N×2 = 3 (N)(N+1)/2
After deducing this we can say
For N*M we’ll have (M)(M+1)/2 (N)(N+1)/2 = M(M+1)(N)(N+1)/4
So the formula for total rectangles will be M(M+1)(N)(N+1)/4
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of rectangles in a circle of radius R
- Number of unique rectangles formed using N unit squares
- Find the minimum number of rectangles left after inserting one into another
- Count the number of rectangles such that ratio of sides lies in the range [a,b]
- Sum of the count of number of adjacent squares in an M X N grid
- Find the number of squares inside the given square grid
- Minimum number of integers required to fill the NxM grid
- Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
- Minimum number of Circular obstacles required to obstruct the path in a Grid
- Find if two rectangles overlap
- Sum of Areas of Rectangles possible for an array
- Find all rectangles filled with 0
- Create a matrix with alternating rectangles of O and X
- Smallest square formed with given rectangles
- Count Distinct Rectangles in N*N Chessboard
Improved By : jit_t