poj 2739 Sum of Consecutive Prime Numbers

求一个数能够被连续的素数的和组成有几种方法:

直接用暴力;

View Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int prime[2024],cnt,sum;
void Prime(  )
{
   bool hash[5024] = { 0 };
   int t = ( int )sqrt( 10000.0 ) + 1;  
   for( int i = 3 ; i <= t; i +=2 )
   {
       if( !hash[i>>1] ) 
       {
           int tt = i << 1;
           for( int j = i*i ; j <= 10000 ; j += tt )    
                hash[j>>1] = true;    
       }        
   }    
   cnt = 0;
   prime[cnt++] = 2;
   t = 10000/2;
   for( int i = 1 ; i <= t ; i ++ )
   {
        if( !hash[i] )
        {
           prime[cnt++] = ( i<<1 ) + 1;    
        }        
   }
}
int Research( int num )
{
    int i = cnt -1;
    int ans = 0;
    while( prime[i] > num )
           i--;
    for( ; i >= 0; i -- )
    {
       int sum = prime[i];
       int j = i -1;
       while( sum < num && j >=0 )
       {
             sum += prime[j];
             j --;
       }
       if( sum == num ) ans++;    
    }
    return ans;    
}
int main( )
{
    Prime();
    int n;
    while( scanf( "%d",&n ) ,n )
    {  
       printf( "%d\n",Research( n  ) );        
    }
   return 0;
}

 

posted @ 2012-07-13 22:51  wutaoKeen  阅读(132)  评论(0编辑  收藏  举报