Maximum Square Side length with M 1×1 and N 2×2 tiles
Last Updated :
09 Nov, 2023
Given M 1×1 and N 2×2 tiles, what’s the largest side length of a square that you can make if the square must be completely filled in the middle?
Examples:
Input: M = 5, N = 1
Output: 3
Explanation: As there are 5, 1*1 squares which can be placed around one 2*2 square to give a 3*3 square.
Input: M = 2, N = 3
Output: 3
Approach: To solve the problem follow the below steps:
- The maximum side of the square that can be built should be sqrt(4*N+M).
- If this value is even, then the whole square can be divided into a series of 2*2 squares, the length being the output.
- If it’s odd, then the maximum length in building the square of 2*2 would be sqrt(4*N + M) – 1.
- Let x = sqrt(4*N+M)-1, the maximum possible squares in this case are (x*x)/4.
- As the length can’t exceed N, the check would be 4*min((x*x/4), N)+M should be greater than or equal to the earlier length (as in step 1).
- If this condition holds, then the length as in step 1 would be the output, otherwise, the output would have 1 less than the length.
Below is the implementation for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findTiles( int M, int N)
{
int x = sqrt (4 * N + M);
if (x % 2 == 0)
return x;
else {
int inter = ((x - 1) * (x - 1)) / 4;
if (4 * min(inter, N) + M >= x * x)
return x;
else
return x - 1;
}
}
int main()
{
int M = 5;
int N = 1;
cout << findTiles(M, N);
return 0;
}
|
Java
class GFG {
public static int findTiles( int M, int N)
{
int x = ( int )Math.sqrt( 4 * N + M);
if (x % 2 == 0 )
return x;
else {
int inter = ((x - 1 ) * (x - 1 )) / 4 ;
if ( 4 * Math.min(inter, N) + M >= x * x)
return x;
else
return x - 1 ;
}
}
public static void main(String args[])
{
int M = 5 ;
int N = 1 ;
System.out.println(findTiles(M, N));
}
}
|
Python3
import math
def findTiles(M, N):
x = int (math.sqrt( 4 * N + M))
if x % 2 = = 0 :
return x
else :
inter = ((x - 1 ) * (x - 1 )) / / 4
if 4 * min (inter, N) + M > = x * x:
return x
else :
return x - 1
if __name__ = = "__main__" :
M = 5
N = 1
print (findTiles(M, N))
|
C#
using System;
class GFG
{
public static int findTiles( int M, int N)
{
int x = ( int )Math.Sqrt(4 * N + M);
if (x % 2 == 0)
return x;
else
{
int inter = ((x - 1) * (x - 1)) / 4;
if (4 * Math.Min(inter, N) + M >= x * x)
return x;
else
return x - 1;
}
}
public static void Main( string [] args)
{
int M = 5;
int N = 1;
Console.WriteLine(findTiles(M, N));
}
}
|
Javascript
function findTiles(M, N) {
let x = Math.sqrt(4 * N + M);
if (x % 2 === 0) {
return x;
}
else {
let inter = ((x - 1) * (x - 1)) / 4;
if (4 * Math.min(inter, N) + M >= x * x) {
return x;
}
else {
return x - 1;
}
}
}
let M = 5;
let N = 1;
console.log(findTiles(M, N));
|
Time complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...