Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
Last Updated :
09 Jun, 2022
Given two integers n, m. Find the number of rectangles of size 2*1 that can be placed inside a rectangle of size n*m.
Note:
- No two small rectangles overlap.
- Each small rectangle lies entirely inside the large rectangle. It is allowed to touch the edges of the large rectangle.
Examples:
Input : n = 3, m =3
Output : 4
Input : n = 2, m = 4
Output : 4
Approach:
- If N is even, then place M rows of N/2 small rectangles and cover the whole large rectangle.
- If M is even, then place N rows of M/2 small rectangles and cover the whole large rectangle.
- If both are odd then cover N – 1 row of the board with small rectangles and put floor(M/2) small rectangles to the last row. In the worst case (N and M are odd) one cell remains uncovered.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int NumberOfRectangles( int n, int m)
{
if (n % 2 == 0)
return (n / 2) * m;
else if (m % 2 == 0)
return (m / 2) * n;
return (n * m - 1) / 2;
}
int main()
{
int n = 3, m = 3;
cout << NumberOfRectangles(n, m);
return 0;
}
|
C
#include <stdio.h>
int NumberOfRectangles( int n, int m)
{
if (n % 2 == 0)
return (n / 2) * m;
else if (m % 2 == 0)
return (m / 2) * n;
return (n * m - 1) / 2;
}
int main()
{
int n = 3, m = 3;
printf ( "%d" ,NumberOfRectangles(n, m));
return 0;
}
|
Java
public class GFG {
static int NumberOfRectangles( int n, int m)
{
if (n % 2 == 0 )
return (n / 2 ) * m;
else if (m % 2 == 0 )
return (m / 2 ) * n;
return (n * m - 1 ) / 2 ;
}
public static void main(String args[])
{
int n = 3 , m = 3 ;
System.out.println(NumberOfRectangles(n, m));
}
}
|
Python3
def NumberOfRectangles(n, m):
if (n % 2 = = 0 ):
return (n / 2 ) * m
elif (m % 2 = = 0 ):
return (m / / 2 ) * n
return (n * m - 1 ) / / 2
if __name__ = = "__main__" :
n = 3
m = 3
print (NumberOfRectangles(n, m))
|
C#
using System;
class GFG
{
static int NumberOfRectangles( int n, int m)
{
if (n % 2 == 0)
return (n / 2) * m;
else if (m % 2 == 0)
return (m / 2) * n;
return (n * m - 1) / 2;
}
public static void Main()
{
int n = 3, m = 3;
Console.WriteLine(NumberOfRectangles(n, m));
}
}
|
PHP
<?php
function NumberOfRectangles( $n , $m )
{
if ( $n % 2 == 0)
return ( $n / 2) * $m ;
else if ( $m % 2 == 0)
return ( $m / 2) * $n ;
return ( $n * $m - 1) / 2;
}
$n = 3;
$m = 3;
echo NumberOfRectangles( $n , $m );
?>
|
Javascript
<script>
function NumberOfRectangles(n, m)
{
if (n % 2 == 0)
return (n / 2) * m;
else if (m % 2 == 0)
return (m / 2) * n;
return (n * m - 1) / 2;
}
var n = 3, m = 3;
document.write(NumberOfRectangles(n, m));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...