Count the number of rhombi possible inside a rectangle of given size
Given a rectangle of height H and width W which has the bottom left corner at (0, 0). The task is to count the number of distinct Rhombi that have all points inside or on the border of the rectangle satisfying the following conditions exists:
- Have non-zero area.
- Have diagonals parallel to the x and y axes.
- Have integer coordinates.
Examples:
Input: H = 2, W = 2
Output: 2
There is only one rhombus possible with coordinates (0, 1), (1, 0), (2, 1) and (1, 2).
Input: H = 4, W = 4
Output: 16
Approach: Since the diagonals are parallel to the axis, let’s try fixing the diagonals and creating rhombi on them. For the rhombus to have integer coordinates, the length of the diagonals must be even. Let’s fix the length of the diagonals to i and j, the number of rhombi we can form with these diagonal lengths inside the rectangle would be (H – i + 1) * (W – j + 1). Thus, we iterate over all possible values of i and j and update the count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
long long countRhombi( int h, int w)
{
long long ct = 0;
for ( int i = 2; i <= h; i += 2)
for ( int j = 2; j <= w; j += 2)
ct += (h - i + 1) * (w - j + 1);
return ct;
}
int main()
{
int h = 2, w = 2;
cout << countRhombi(h, w);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countRhombi( int h, int w)
{
int ct = 0 ;
for ( int i = 2 ; i <= h; i += 2 )
for ( int j = 2 ; j <= w; j += 2 )
ct += (h - i + 1 ) * (w - j + 1 );
return ct;
}
public static void main (String[] args)
{
int h = 2 , w = 2 ;
System.out.println (countRhombi(h, w));
}
}
|
Python 3
def countRhombi(h, w):
ct = 0 ;
for i in range ( 2 , h + 1 , 2 ):
for j in range ( 2 , w + 1 , 2 ):
ct + = (h - i + 1 ) * (w - j + 1 )
return ct
if __name__ = = "__main__" :
h = 2
w = 2
print (countRhombi(h, w))
|
C#
using System;
class GFG
{
static int countRhombi( int h, int w)
{
int ct = 0;
for ( int i = 2; i <= h; i += 2)
for ( int j = 2; j <= w; j += 2)
ct += (h - i + 1) * (w - j + 1);
return ct;
}
public static void Main()
{
int h = 2, w = 2;
Console.WriteLine(countRhombi(h, w));
}
}
|
PHP
<?php
function countRhombi( $h , $w )
{
$ct = 0;
for ( $i = 2; $i <= $h ; $i += 2)
for ( $j = 2; $j <= $w ; $j += 2)
$ct += ( $h - $i + 1) * ( $w - $j + 1);
return $ct ;
}
$h = 2; $w = 2;
echo (countRhombi( $h , $w ));
?>
|
Javascript
<script>
function countRhombi(h, w)
{
let ct = 0;
for (let i = 2; i <= h; i += 2)
for (let j = 2; j <= w; j += 2)
ct += (h - i + 1) * (w - j + 1);
return ct;
}
let h = 2, w = 2;
document.write(countRhombi(h, w));
</script>
|
Time Complexity: O(H * W)
Auxiliary Space: O(1)
Last Updated :
23 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...