poj 3518 Prime Gap

素数水题:

View Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#include<cstring>
#include<vector>
using namespace std;
int prime[100000],cnt=0;
bool hash[700024];
void Prime( )
{
    int t = ( int )sqrt( 1299709.0 ) + 1;
    memset( hash , 0 ,sizeof( hash ) );
    for(int i = 3 ; i <= t ; i += 2 )  
    {
       if( !hash[i>>1] )
       {
          int x = i<<1;
          for( int j = i * i; j <=  1299709 ; j += x )
          {
               hash[j>>1] = true;        
          }        
       }    
    }
    cnt = 0;
    prime[cnt++] = 2;
    t =  (1299709+1)/2;
    for( int i = 1; i <=t ; i ++ )
    {
         if( !hash[i] )
         {
             prime[cnt++] =i * 2 + 1;    
         }
    }
}
int Solve( int num )
{ 
    for( int i = 0 ; i < cnt ; i ++ )
    {
        if( prime[i] > num )
        {
            return prime[i] - prime[i-1];    
        }
        else if( prime[i] == num ) return 0;
    }    
    return 0;
}
int main(  )
{
    Prime();
    int num;
    while( scanf( "%d",&num ),num )
    {  
        printf( "%d\n",Solve( num )   ); 
    }
    //system( "pause" );
    return 0;
}

 

posted @ 2012-07-14 08:58  wutaoKeen  阅读(134)  评论(0编辑  收藏  举报