Given two integers N and M , where N straight lines are parallel to the X-axis and M straight lines are parallel to Y-axis , the task is to calculate the number of rectangles that can be formed by these lines.
Examples:
Input: N = 3, M = 6 Output: 45 Explanation: There are total 45 rectangles possible with 3 lines parallel to x axis and 6 lines parallel to y axis.Input: N = 2, M = 4 Output: 6 Explanation: There are total 6 rectangles possible with 2 lines parallel to x axis and 4 lines parallel to y axis.
Approach: To solve the problem mentioned above we need to observe that a rectangle is formed by 4 straight lines in which opposite sides are parallel and the angle between any two sides is 90. Hence, for every rectangle, two sides need to be parallel to X-axis and the other two sides need to be parallel to Y-axis.
Number of ways to select two lines parallel to X axis = N C2 and the Number of ways to select two lines parallel to Y axis = M C2 . So the total number of rectangles = N C2 * M C2 = [ N * (N – 1) / 2 ] * [ M * (M – 1) / 2 ]
Below is implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int count_rectangles(int N, int M)
{
int p_x = (N * (N - 1)) / 2;
int p_y = (M * (M - 1)) / 2;
return p_x * p_y;
}
int main()
{
int N = 3;
int M = 6;
cout << count_rectangles(N, M);
}
Java
class GFG{
static int count_rectangles(int N, int M)
{
int p_x = (N * (N - 1)) / 2;
int p_y = (M * (M - 1)) / 2;
return p_x * p_y;
}
public static void main(String[] args)
{
int N = 3;
int M = 6;
System.out.print(count_rectangles(N, M));
}
}
Python3
def count_rectangles(N, M):
p_x = (N * (N - 1)) // 2
p_y = (M * (M - 1)) // 2
return p_x * p_y
N = 3
M = 6
print(count_rectangles(N, M))
C#
using System;
class GFG{
static int count_rectangles(int N, int M)
{
int p_x = (N * (N - 1)) / 2;
int p_y = (M * (M - 1)) / 2;
return p_x * p_y;
}
public static void Main()
{
int N = 3;
int M = 6;
Console.Write(count_rectangles(N, M));
}
}
Javascript
<script>
function count_rectangles(N, M)
{
let p_x = (N * (N - 1)) / 2;
let p_y = (M * (M - 1)) / 2;
return p_x * p_y;
}
let N = 3;
let M = 6;
document.write(count_rectangles(N, M));
</script>
Time Complexity: O(1), as constant operations are being performed.Auxiliary Space: O(1), as constant space is being used.
Last Updated :
06 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...