Number of rectangles with given area in an N*M grid

• Difficulty Level : Medium
• Last Updated : 30 Jun, 2021

Given three positive integers N, M, and A, the task is to count the number of rectangles with area equal to A present in an M * N grid.

Examples:

Input: N = 2, M = 2, A = 2
Output:
Explanation:
In the given grid of size 2 × 2, 2 rectangles of dimension 2 × 1 and 2 rectangles of dimension 1 × 2 can be inscribed.
Therefore, the required output is 4.

Input: N = 2, M = 2, A = 3
Output: 0
Explanation:
The possible rectangles with area A (= 3) are of dimensions either 1 × 3 or 3 × 1.
But, the maximum length of a side in the grid can only be 2. Therefore, no rectangles can be inscribed within the grid.

Approach: The problem can be solved based on the following observations:

The total number of ways to select a segment of length X on the segment of length M is equal to (M – X + 1)
Therefore, the total count of rectangles of size X * Y in the rectangle of size M * N is equal to (M – X + 1) * (N – Y + 1).

Follow the steps below to solve the problem:

• Iterate over the range [1, √A]. For every ith iteration, find all possible values of length and breadth of the rectangles, say { i, (A / i)} or { (A / i), i } within the given grid.
• Iterate over all possible values of length say X and breadth say, Y and increment the count of rectangles by (M – X + 1) * (N – Y + 1).
• Finally, print the count obtained.

Below is the implementation of the above approach:

Javascript



Output:

4

Time Complexity: O(sqrt(N))
Auxiliary Space: O(sqrt(N))

My Personal Notes arrow_drop_up
Recommended Articles
Page :