给定n个大小为1 x 1的块,我们需要找到由这些块构成的网格的最小周长。
例子 :
输入:n = 4输出:8带有4个块的最小可能周长是8。请参见以下说明。输入:n = 11输出:14上面示例的正方形网格为
让我们以一个例子来看一个模式。假设我们有4个区块,以下是不同的可能性
+--+--+--+--+
| | | | | Perimeter = 10
+--+--+--+--+
+--+--+--+
| | | | Perimeter = 10
+--+--+--+
| |
+--+
+--+--+--+
| | | | Perimeter = 10
+--+--+--+
| |
+--+
+--+--+
| | | Perimeter = 8
+--+--+
| | |
+--+--+
如果我们使用笔和纸做一些示例,我们会注意到,当所形成的形状最接近正方形时,周长会最小。原因是,我们希望块的最大边面向形状内部,以使形状的周长最小。
如果块数是一个完美的正方形,则周长将简单地为4 * sqrt(n)。
但是,如果“块数”不是理想的平方根,则我们将计算最接近平方根的行数和列数。在将块排列成矩形后,我们仍然剩下块,然后我们只需将2加到周长,因为只剩下2个额外的边。
下面给出上述想法的实现。
C++
// CPP program to find minimum
// perimeter using n blocks.
#include
using namespace std;
int minPerimeter(int n)
{
int l = sqrt(n);
int sq = l * l;
// if n is a perfect square
if (sq == n)
return l * 4;
else
{
// Number of rows
long long int row = n / l;
// perimeter of the
// rectangular grid
long long int perimeter
= 2 * (l + row);
// if there are blocks left
if (n % l != 0)
perimeter += 2;
return perimeter;
}
}
// Driver code
int main()
{
int n = 10;
cout << minPerimeter(n);
return 0;
}
Java
// JAVA Code to find minimum
// perimeter using n blocks
import java.util.*;
class GFG
{
public static long minPerimeter(int n)
{
int l = (int) Math.sqrt(n);
int sq = l * l;
// if n is a perfect square
if (sq == n)
return l * 4;
else
{
// Number of rows
long row = n / l;
// perimeter of the
// rectangular grid
long perimeter
= 2 * (l + row);
// if there are blocks left
if (n % l != 0)
perimeter += 2;
return perimeter;
}
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println(minPerimeter(n));
}
}
// This code is contributed by Arnav Kr. Mandal
Python3
# Python3 program to find minimum
# perimeter using n blocks.
import math
def minPerimeter(n):
l = math.sqrt(n)
sq = l * l
# if n is a perfect square
if (sq == n):
return l * 4
else :
# Number of rows
row = n / l
# perimeter of the
# rectangular grid
perimeter = 2 * (l + row)
# if there are blocks left
if (n % l != 0):
perimeter += 2
return perimeter
# Driver code
n = 10
print(int(minPerimeter(n)))
# This code is contributed by
# Prasad Kshirsagar
C#
// C# Code to find minimum
// perimeter using n blocks
using System;
class GFG
{
public static long minPerimeter(int n)
{
int l = (int) Math.Sqrt(n);
int sq = l * l;
// if n is a perfect square
if (sq == n)
return l * 4;
else
{
// Number of rows
long row = n / l;
// perimeter of the
// rectangular grid
long perimeter
= 2 * (l + row);
// if there are blocks left
if (n % l != 0)
perimeter += 2;
return perimeter;
}
}
// Driver code
public static void Main()
{
int n = 10;
Console.Write(minPerimeter(n));
}
}
// This code is contributed by nitin mittal
PHP
输出 :
14
参考 :
http://mathforum.org/library/drmath/view/61595.html
intermath.coe.uga.edu/tweb/gcsu-geo-spr06/aheath/aheath_rectperimeter.doc