Smallest square formed with given rectangles
Last Updated :
31 Aug, 2022
Given a rectangle of length l and breadth b, we need to find the area of the smallest square which can be formed with the rectangles of these given dimensions.
Examples:
Input : 1 2
Output : 4
We can form a 2 x 2 square
using two rectangles of size
1 x 2.
Input : 7 10
Output :4900
Let’s say we want to make a square of side length a from rectangles of length l & b. This means that a is a multiple of both l & b. Since we want the smallest square, it has to be the lowest common multiple (LCM) of l & b.
Program 1:
C++
#include <bits/stdc++.h>
using namespace std;
int gcd( int a, int b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
int squarearea( int l, int b)
{
if (l < 0 || b < 0)
return -1;
int n = (l * b) / gcd(l, b);
return n * n;
}
int main()
{
int l = 6, b = 4;
cout << squarearea(l, b) << endl;
return 0;
}
|
Java
class GFG
{
static int gcd( int a, int b)
{
if (a == 0 || b == 0 )
return 0 ;
if (a == b)
return a;
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
static int squarearea( int l, int b)
{
if (l < 0 || b < 0 )
return - 1 ;
int n = (l * b) / gcd(l, b);
return n * n;
}
public static void main(String[] args)
{
int l = 6 , b = 4 ;
System.out.println(squarearea(l, b));
}
}
|
Python 3
def gcd( a, b):
if (a = = 0 or b = = 0 ):
return 0
if (a = = b):
return a
if (a > b):
return gcd(a - b, b)
return gcd(a, b - a)
def squarearea( l, b):
if (l < 0 or b < 0 ):
return - 1
n = (l * b) / gcd(l, b)
return n * n
if __name__ = = '__main__' :
l = 6
b = 4
print ( int (squarearea(l, b)))
|
C#
using System;
class GFG
{
static int gcd( int a, int b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
static int squarearea( int l, int b)
{
if (l < 0 || b < 0)
return -1;
int n = (l * b) / gcd(l, b);
return n * n;
}
public static void Main()
{
int l = 6, b = 4;
Console.Write(squarearea(l, b));
}
}
|
PHP
<?php
function gcd( $a , $b )
{
if ( $a == 0 || $b == 0)
return 0;
if ( $a == $b )
return $a ;
if ( $a > $b )
return gcd( $a - $b , $b );
return gcd( $a , $b - $a );
}
function squarearea( $l , $b )
{
if ( $l < 0 || $b < 0)
return -1;
$n = ( $l * $b ) / gcd( $l , $b );
return $n * $n ;
}
$l = 6;
$b = 4;
echo squarearea( $l , $b ). "\n" ;
?>
|
Javascript
<script>
function gcd(a , b)
{
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
if (a > b)
return gcd(a - b, b);
return gcd(a, b - a);
}
function squarearea(l , b)
{
if (l < 0 || b < 0)
return -1;
var n = (l * b) / gcd(l, b);
return n * n;
}
var l = 6, b = 4;
document.write(squarearea(l, b));
</script>
|
Time Complexity: O(log(min(l,b)))
Auxiliary Space: O(log(min(l, b)))
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...