poj2739 Sum of Consecutive Prime Numbers 雜題

題目鏈接:http://poj.org/problem?id=2739

題目大意:給你一個數字,這個數字可能可以表示爲一些素數相加的和,問對應每一個數字,有幾組素數相加可以得到這個素數。

///2014.7.16
///poj2739

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

/*=================================*\
  素數打表
  該函數執行後在prim[]數組中存入
  從2開始的從小到大的numOfPrim個素數
\*=================================*/
const int numOfPrim = 1230;
int prim[numOfPrim] = {2,3};
void prime(){
    int tally=2;
    bool flag;
    for(int i=5 ; tally<numOfPrim ; i+=2){
        flag = true;
        for(int j=0 ; prim[j]*prim[j]<=i ; j++)
            if( i%prim[j]==0 ){ flag = false; break; }
        if( flag ){
            prim[tally]=i;
            tally++;
        }
    }
}
/*=================================*/

int num,c;

void Count(int num,int i){
    if( i<0 ) return ;
    if( num==prim[i] )
        c ++;
    else if( num>prim[i] )
        Count(num-prim[i],i-1);
}
void work(){
    c = 0;
    int k;
    for(k=0 ; prim[k]<=num ; k++);
    if( prim[k]==num ) c++;
    k--;
    for(int i=k ; i>=0 ; i--)
        Count(num,i);
}
int main(){
    // freopen("in","r",stdin);
    // freopen("out","w",stdout);

    prime();
    while( cin>>num && num ){
        work();
        cout<<c<<endl;
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章