Count Distinct Rectangles in N*N Chessboard

Last Updated : 25 Mar, 2025

Given a n x n Chessboard. The task is to count distinct rectangles from the chessboard. For example, if the input is 8 then the output should be 36.
Examples: 

Input: n = 4
Output: 10

Input: n = 6
Output: 21

Try It Yourself
redirect icon

Suppose n = 8 i.e. 8 x 8 chessboard is given, So different rectangles that can be formed are: 

1 x 1, 1 x 2, 1 x 3, 1 x 4, 1 x 5, 1 x 6, 1 x 7, 1 x 8 = 8
2 x 2, 2 x 3, 2 x 4, 2 x 5, 2 x 6, 2 x 7, 2 x 8 = 7
3 x 3, 3 x 4, 3 x 5, 3 x 6, 2 x 7, 3 x 8 = 6
4 x 4, 4 x 5, 4 x 6, 4 x 7, 4 x 8 = 5
5 x 5, 5 x 6, 5 x 7, 5 x 8 = 4
6 x 6, 6 x 7, 6 x 8 = 3
7 x 7, 7 x 8 = 2
8 x 8 = 1

So total distinct rectangles formed = 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36. which is the sum of the first 8 natural numbers. So in general, distinct rectangles that can be formed in an n x n chessboard are: sum of the first n natural numbers = n*(n+1)/2

C++
#include <bits/stdc++.h> 
using namespace std; 

int distinctRectangles(int n)
{
    int ans = 0;
    ans = (n * (n + 1)) / 2;
    return ans;
}


int main()
{
    int n = 4;
    cout<<distinctRectangles(n); 
}
Java
class GfG {

    static int distinctRectangles(int n)
    {
        int ans = 0;

        ans = (n * (n + 1)) / 2;

        return ans;
    }
    
    public static void main(String args[])
    {
        int n = 4;
        System.out.print(distinctRectangles(n)); 
    }
}
Python
def distinctRectangles(n):
    ans = 0;
    ans = (n * (n + 1)) / 2;
    return int(ans);



n = 4;
print(distinctRectangles(n)); 
C#
using System;

class GfG 
{ 

    // Function to count distinct rectangles 
    static int distinctRectangles(int n) 
    { 
        int ans = 0;
        ans = (n * (n + 1)) / 2;
        return ans; 
    } 

    public static void Main() 
    { 
        int n = 4; 
        Console.Write(distinctRectangles(n)); 
    } 
} 
JavaScript
function distinctRectangles(n) 
    { 
        var ans = 0; 
        ans = (n * (n + 1)) / 2; 
        return ans; 
    } 

        var n = 4; 
        console.log(distinctRectangles(n)); 

Output
10

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment