We are given n blocks of size 1 x 1, we need to find the minimum perimeter of the grid made by these blocks.
Input : n = 4 Output : 8 Minimum possible perimeter with 4 blocks is 8. See below explanation. Input : n = 11 Output : 14 The square grid of above examples would be as
Let us take an example to see a pattern. Let us say that we have 4 blocks, following are different possibilities
+--+--+--+--+ | | | | | Perimeter = 10 +--+--+--+--+ +--+--+--+ | | | | Perimeter = 10 +--+--+--+ | | +--+ +--+--+--+ | | | | Perimeter = 10 +--+--+--+ | | +--+ +--+--+ | | | Perimeter = 8 +--+--+ | | | +--+--+
If we do some examples using pen and paper, we can notice that the perimeter becomes minimum when the shape formed is closest to a square. The reason for this is, we want maximum sides of blocks to face inside the shape so that perimeter of the shape becomes minimum.
If the Number of blocks is a perfect square then the perimeter would simply be 4*sqrt(n).
But, if the Number of blocks is not a perfect square root then we calculate number of rows and columns closest to square root. After arranging the blocks in a rectangular we still have blocks left then we will simply add 2 to the perimeter because only 2 extra side would be left.
The implementation of the above idea is given below.
This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Perimeter of an Ellipse
- Find the perimeter of a cylinder
- Find Perimeter of a triangle
- Program for Area And Perimeter Of Rectangle
- Maximum area of rectangle possible with given perimeter
- Perimeter of Convex hull for a given set of points
- Perimeter and Area of Varignon's Parallelogram
- Program to Calculate the Perimeter of a Decagon
- Program to find the Perimeter of a Regular Polygon
- Program to find the Area and Perimeter of a Semicircle
- Program to calculate area and perimeter of Trapezium
- Find maximum volume of a cuboid from the given perimeter and area
- Program to find Perimeter / Circumference of Square and Rectangle
- Program to calculate area and perimeter of a rhombus whose diagonals are given
- Program to calculate area and perimeter of equilateral triangle