1004 質方數
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) 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
#include<iostream>#include<cmath>using namespace std;#define Max 10000int a[Max+1]= {1,1,0};int main(){ for( int i=2; i<=5000; i++ ) for( int j=i<<1; j<Max+1; j+=i ) { a[j]=1; } int T; int N; cin>>T; while( T-- ) { cin>>N; int temp=sqrt(N); if( temp*temp == N && a[temp]==0 ) cout<<N<<endl; else if( temp==1 ) cout<<4<<endl; else { int i, j; for( i=temp; i>=2; i-- ) { if( a[i]==0 ) break; } for( j=temp+1; j<=Max; j++ ) { if( a[j]==0 ) break; } if( N-i*i <= j*j-N ) cout<<i*i<<endl; else cout<<j*j<<endl; } }}
總是望著曾經的空間發獃,那些說好不分開的朋友不在了,轉身,陌路。 熟悉的,安靜了, 安靜的,離開了, 離開的,陌生了, 陌生的,消失了, 消失的,陌路了。