poj 2262 Goldbach's Conjecture

一道简单的素数题:

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[1000024];

void Prime( )

{

    int t = ( int )sqrt( 1000000.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 <= 1000001 ; j += x )

          {

               hash[j>>1] = true;        

          }        

       }    

    }

    cnt = 0;

    prime[cnt++] = 2;

    t = 1000000/2;

    for( int i = 1; i <=t ; i ++ )

    {

         if( !hash[i] )

         {

             prime[cnt++] =i * 2 + 1;    

         }

    }

    memset( hash , 0 ,sizeof( hash ) );

    for( int i = 0 ; i < cnt; i ++ )

    {

        hash[prime[i]] = true;

    }

}

bool Solve( int num )

{ 

    int t =  num/2;

    for( int i = 0 ;i < cnt ;i ++ )

    {

        if( prime[i] > t ) return false;

        else

        {

            if( hash[num-prime[i]] )

            {

                printf( "%d = %d + %d\n",num,prime[i],num-prime[i] );

                return true;    

            }

        }    

    }     

    return false;

}

int main(  )

{

    Prime();

    int num;

    while( scanf( "%d",&num ),num )

    {  

           if(Solve( num ) == false )

        printf( "Goldbach's conjecture is wrong.\n"  ); 

    }

    //system( "pause" );

    return 0;

}

 

你可能感兴趣的:(dba)