用素数筛,枚举所有区间,把加和,并把ans对应的位+1.
View Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
#define maxn 10005
bool is[maxn];
int prm[maxn];
int sum[maxn];
int ans[maxn];
int getprm(int n)
{
int i, j, k = 0;
int s, e = (int) (sqrt(0.0 + n) + 1);
memset(is, 1, sizeof(is));
prm[k++] = 2;
is[0] = is[1] = 0;
for (i = 4; i < n; i += 2)
is[i] = 0;
for (i = 3; i < e; i += 2)
if (is[i])
{
prm[k++] = i;
for (s = i * 2, j = i * i; j < n; j += s)
is[j] = 0;
// 因为j是奇数,所以+奇数i后是偶数,不必处理!
}
for (; i < n; i += 2)
if (is[i])
prm[k++] = i;
return k; // 返回素数的个数
}
int main()
{
//freopen("D:\\t.txt", "r", stdin);
memset(ans, 0, sizeof(ans));
int tot = getprm(10000);
sum[0] = prm[0];
ans[sum[0]] = 1;
for (int i = 1; i < tot; i++)
{
sum[i] = sum[i - 1] + prm[i];
if (sum[i] < maxn)
ans[sum[i]]++;
}
for (int i = 0; i < tot; i++)
for (int j = 0; j < i; j++)
if (sum[i] - sum[j] < maxn)
ans[sum[i] - sum[j]]++;
int n;
while (scanf("%d", &n) != EOF && n != 0)
printf("%d\n", ans[n]);
return 0;
}