紫书 习题 10-6 UVa 1210(前缀和)

素数筛然后前缀和

看代码

#include<cstdio>
#include<vector>
#include<cstring>
#include<map>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 11234;
bool is_prime[MAXN];
vector<int> prime;
int a[MAXN];
map<int, int> f;

void init()
{
	memset(is_prime, true, sizeof(is_prime));
	is_prime[0] = is_prime[1] = false;
	REP(i, 2, MAXN)
	{
		if(is_prime[i]) prime.push_back(i);
		REP(j, 0, prime.size())
		{
			if(i * prime[j] >= MAXN) break;
			is_prime[i * prime[j]] = false;
			if(i % prime[j] == 0) break;
		}
	}
}

int main()
{
	init();
	
	a[0] = prime[0];
	REP(i, 1, prime.size())
		a[i] = a[i-1] + prime[i];
	
	REP(i, 0, prime.size())
		REP(j, i, prime.size())
		{
			if(i == 0) f[a[j]]++;
			else f[a[j] - a[i-1]]++;
		}
		
	int n;
	while(~scanf("%d", &n) && n)
		printf("%d\n", f[n]);
		
	return 0;
}

 

posted @ 2018-07-22 14:42  Sugewud  阅读(100)  评论(0编辑  收藏  举报