hdu 质方数

Problem Description
  小明天生对数字比较敏感,3岁的时候就能背诵圆周率一百位。

  现在,小明慢慢长大了,但依然很喜欢数字,最近,他迷上了质数和平方数,并且自己把质数的平方命名为“质方数”。
  现在,他在研究这样一个问题:距离一个正整数N最接近的质方数是多少?
 
Input
输入数据第一行是一个正整数T(T<=20),表示有T组输入数据。
接下来T行,每行输入一个正整数N(1<=N<=10^8)。
 
Output
对于每组数据,请输出距离N最接近的质方数,每组输出占一行。
 
Sample Input
2 1 10
 
Sample Output
4 9

水了一发杭电全国新生赛,我只想说当时题意理解错误。

玉民的代码:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <iomanip>
 4 #include <string>
 5 #include <cstring>
 6 #include <cmath>
 7 using namespace std;
 8 int cmp(int x)
 9 {
10     if(x==1) return 0;
11     else
12     {
13         for(int i=2;i<=sqrt(x);i++)
14           if(x%i==0) return 0;
15     }
16     return 1;
17 }
18 int main()
19 {
20     int n,m,i,j,k,t;
21     cin>>t;
22     while(t--)
23     {
24         cin>>m;
25         k=sqrt(m);
26         if(m==1||m==2||m==3)
27            cout<<"4"<<endl;
28         else
29         {   int k;
30             for(i=m;;i++)
31             {   k=sqrt(i);
32                 if(k*k==i&&cmp(k)) break;
33             }
34             for(j=m;;j--)
35             {   k=sqrt(j);
36                 if(k*k==j&&cmp(k)) break;
37             }
38             
39             if(i-m<m-j) cout<<i<<endl;
40             else cout<<j<<endl;
41         }
42     } 
43     return 0;
44 }
View Code
原文地址:https://www.cnblogs.com/wangmengmeng/p/5007542.html