通过面积求周长......

Description

There is a piece of paper in front of Tom, its length and width are integer. Tom knows the area of this paper, he wants to know the minimum perimeter of this paper.
 

Input

In the first line, there is an integer T indicates the number of test cases. In the next T lines, there is only one integer n in every line, indicates the area of paper.  $Tleq 10,nleq {10}^{9}$
 

Output

For each case, output a integer, indicates the answer.
 

Sample Input

3 2 7 12
 

Sample Output

6 16 14
 
 
题目意思:告诉你一个矩形的面积求他的最小周长
 
解题思路:可以想到的方法最直接的就是枚举然后比较,可惜的是,这样会超时.......
然后就是一种更加快的方法。可以想想,当x和y之间的差越小,周长就越小。所以可以用开平方来节省时间。先把面积开平方,开完之后转成整形,然后计算面积是否可以整除开出来的数,不可以就减一,直到满足整除.....这样就找到了,最小周长的一条边,然后就可以输出最小周长了。
为什么说找到的就是最小周长的一条边呢?
可以这样比喻,当你开平方就是数的找到中点,然后向左走,找到的第一个满足整除的就是x和y之间距离最短的一对
 
先来一个超时的代码吧。     (好对比一下)
 
 1 #include <stdio.h>
 2 
 3 int main()
 4 {
 5     int T;
 6     scanf("%d",&T);
 7     while(T--)
 8     {
 9         int S,sum=10000,k=0;
10         scanf("%d",&S);
11         for(int x=1; x<=S; x++)
12         {
13             if(S%x==0&&sum>=(x+S/x))
14                 sum=x+S/x;
15         }
16         printf("%d
",2*sum);
17     }
18     return 0;
19 }

接下来是不超时的代码:

 1 #include<cstdio>
 2 #include<cmath>
 3 int main()
 4 {
 5     int t,s,n;
 6     scanf("%d",&t);
 7     while(t--)
 8     {
 9         scanf("%d",&s);
10         n=(int)sqrt((double) s);
11         while(s%n)
12            {
13                //printf("%d
",n);
14                 n--;
15            }
16         n=2*(n+s/n);
17     printf("%d
",n);
18     }
19 return 0;
20 }
原文地址:https://www.cnblogs.com/huangguodong/p/4693039.html