Rectangles In N x N Board

Posted: 25 Feb, 2021
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

You are given a positive integer N. Your task is to find the number of possible rectangles, excluding squares, in a N x N chessboard.

Example:
Let’s assume that we have a chessboard of dimension 4x4, i.e. N = 4. Then the rectangles can have the following possible dimensions: {1*2, 1*3, 1*4, 2*1, ……, 2*4, ………,4*4}. So, the total number of rectangles in the chessboard is 70.
Input format:
The very first line of input contains an integer T’ denoting the number of test cases. 

The first line of every test case contains an integer ‘N’ denoting the dimension of the chessboard.
Output format:
For each test case, print the number of possible rectangles, excluding squares, in a N x N chessboard.

Output for each test case is printed on a separate line.
Note:
The result can be very large. So, print the answer modulo 1000000007.

You do not need to print anything, it has already been taken care of. Just return the number of possible rectangles. 
Constraints:
1 <= T <= 10 
1 <= N <= 5 * 10^4

Time Limit: 1 sec
Approach 1
  • A simple approach to solve this problem is to find the total number of possible rectangles, including squares, and then subtract the number of possible squares.
  • We can easily determine the total number of rectangles if we think of a rectangle as a pair of horizontal lines and a pair of vertical lines, intersecting at four points.
  • The given board will have (N+1) horizontal and (N+1) vertical lines.
  • So, the total number of rectangles (including squares) would be the number of ways to choose two distinct horizontal lines and two distinct vertical lines.
  • This can be found by using combinations as: (N + 1)C2 * (N + 1)C2, where ‘C’ stands for combination. This is equal to (N * (N + 1) / 2) * (N * (N + 1) / 2) = (N * (N + 1) / 2) ^ 2
  • Now, to determine the number of possible squares, we try to determine the pattern between the dimension of the square and the number of such squares present in the N x N board.
    • Number of squares with dimension 1x1 = N^2
    • Number of squares with dimension 2x2 = (N - 1)^2
    • Number of squares with dimension 3x3 = (N - 2)^2
    • And so on, till number of squares with dimension NxN = (N - (N-1))^2 = 1^2
  • Adding the above values, we get total number of possible squares in a N x N board = 1^2 + 2^2 + ……. (N-1)^2 + N^2 = N * (N + 1) * (2 * N + 1) / 6 (using the formula for sum of the squares of first ‘N’ natural numbers).
  • Therefore, the number of rectangles (excluding squares) = (N*(N+1)/2)^2 - (N*(N + 1)*(2*N + 1)/6). This can be easily calculated in constant time.
Try Problem