Number of rectangles#11258

Number of rectangles (Editorial)

Consider the size of a rectangle a \times b drawn on the grid. Let's examine how many ways we can choose the value of . The grid contains rows of squares, and therefore there are n + 1 horizontal lines in the grid. Let's number them from to n + 1. We choose two lines and j~(i < j). Drawing a segment between them forms the vertical side a of the rectangle. The number of ways to choose two numbers and j~(i < j) from the set \{1, 2, ..., n + 1\} is equal to C_{n+1}^2. For example, for n = 2 there are options to choose the vertical side of the rectangle:

Similarly, the grid has m + 1 vertical lines. The number of ways to select the horizontal side of a rectangle is C_{m+1}^2.

Therefore the number of different rectangles on the grid is equal to

C_{n+1}^2 \cdot C_{m+1}^2 = {(n + 1) \cdot n \over 2} \cdot {(m + 1) \cdot m \over 2}

Example

For a 2 \times 3 rectangle there are:

The total result is C_3^2 \cdot C_4^2 = 3 \cdot 6 = 18 rectangles.

Algorithm implementation

Since n, m \le 10^5, the number of rectangles can be as large as C_{n+1}^2 \cdot C_{m+1}^2 \le (10^5)^2 \cdot (10^5)^2 = 10^{20}. This result is beyond the bounds of a -bit integer. Therefore, let's implement the solution in Python.

n, m = map(int,input().split())
a = (n + 1) * n // 2
b = (m + 1) * m // 2
res = a * b
print(res)