電腦學院大學生程式設計競賽(2015’11)1004 質方數

來源:互聯網
上載者:User
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;        }    }}

總是望著曾經的空間發獃,那些說好不分開的朋友不在了,轉身,陌路。 熟悉的,安靜了, 安靜的,離開了, 離開的,陌生了, 陌生的,消失了, 消失的,陌路了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.