Minimum squares to evenly cut a rectangle
Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.
Examples:
Input :l= 4 w=6
Output :6
We can form squares with side of 1 unit, But the number of squares will be 24, this is not minimum. If we make square with side of 2, then we have 6 squares. and this is our required answer.
And also we can’t make square with side 3, if we select 3 as square side, then whole sheet can’t be converted into squares of equal length.
Input :l=3 w=5
Output :15
Optimal length of the side of a square is equal to GCD of two numbers
C++
#include <bits/stdc++.h>
using namespace std;
int countRectangles( int l, int w)
{
int squareSide = __gcd(l, w);
return (l * w) / (squareSide * squareSide);
}
int main()
{
int l = 4, w = 6;
cout << countRectangles(l, w) << endl;
return 0;
}
|
Java
class GFG{
static int __gcd( int a, int b) {
if (b== 0 ) return a;
return __gcd(b,a%b);
}
static int countRectangles( int l, int w)
{
int squareSide = __gcd(l, w);
return (l * w) / (squareSide * squareSide);
}
public static void main(String[] args)
{
int l = 4 , w = 6 ;
System.out.println(countRectangles(l, w));
}
}
|
Python3
import math
def countRectangles(l, w):
squareSide = math.gcd(l,w)
return (l * w) / (squareSide * squareSide)
if __name__ = = '__main__' :
l = 4
w = 6
ans = countRectangles(l, w)
print ( int (ans))
|
C#
class GFG{
static int __gcd( int a, int b) {
if (b==0) return a;
return __gcd(b,a%b);
}
static int countRectangles( int l, int w)
{
int squareSide = __gcd(l, w);
return (l * w) / (squareSide * squareSide);
}
public static void Main()
{
int l = 4, w = 6;
System.Console.WriteLine(countRectangles(l, w));
}
}
|
PHP
<?php
function gcd( $a , $b )
{
return $b ? gcd( $b , $a % $b ) : $a ;
}
function countRectangles( $l , $w )
{
$squareSide = gcd( $l , $w );
return ( $l * $w ) / ( $squareSide *
$squareSide );
}
$l = 4;
$w = 6;
echo countRectangles( $l , $w ) . "\n" ;
?>
|
Javascript
<script>
function __gcd(a, b) {
if (b==0) return a;
return __gcd(b,a%b);
}
function countRectangles(l, w)
{
let squareSide = __gcd(l, w);
return parseInt((l * w) / (squareSide * squareSide));
}
let l = 4, w = 6;
document.write(countRectangles(l, w));
</script>
|
Time Complexity: O(log(min(a, b))), where a and b are two parameters of gcd.
Auxiliary Space: O(log(min(a, b)))
Last Updated :
19 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...