程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 通過面積求周長......,面積周長......

通過面積求周長......,面積周長......

編輯:C++入門知識

通過面積求周長......,面積周長......


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.  $T\leq 10,n\leq {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\n",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",n);
14                 n--;
15            }
16         n=2*(n+s/n);
17     printf("%d\n",n);
18     }
19 return 0;
20 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved