当前位置: 代码迷 >> 综合 >> poj - 2739 - Sum of Consecutive Prime Numbers
  详细解决方案

poj - 2739 - Sum of Consecutive Prime Numbers

热度:48   发布时间:2024-01-10 13:54:13.0

题意:输入一个整数n( 在2和10 000之间),求n可以表示成多少种连续素数和。

题目链接:http://poj.org/problem?id=2739

——>>先打素数表,然后统计所有可能值就好。

#include <cstdio>
#include <cstring>using namespace std;const int maxn = 10000 + 10;
int p[maxn], m, cnt[maxn];void prime_table()      //筛法素数打表
{bool vis[maxn];memset(vis, 0, sizeof(vis));int i, j;for(i = 2; i < 10000; i++) if(!vis[i])for(j = (i<<1); j <= 10000; j += i) vis[j] = 1;m = 0;for(i = 2; i < 10000; i++) if(!vis[i]) p[m++] = i;
}
int main()
{int n, i, j, temp;prime_table();memset(cnt, 0, sizeof(cnt));for(i = 0; i < m; i++)      //预处理计算所有可能值{temp = p[i];cnt[temp]++;        //对应值+1for(j = i+1; j < m; j++){temp += p[j];if(temp > 10000) break;cnt[temp]++;        //对应值+1}}while(~scanf("%d", &n)){if(!n) return 0;printf("%d\n", cnt[n]);}return 0;
}