POJ 2739 Sum of Consecutive Prime Numbers
题目大意:就是输入一个n,计算出连续素数相加等于n的序列有几个。
首先就是用到了筛法求素数。筛法求素数的思想就是说一个序列中,当然大于等于2,假设都是素数,然后最小的数是素数,放到素数的框里,这个素数的倍数是合数,筛出去到合数的框里,完了之后又出现了新的最小数,然后这个最小数的倍数还是合数,……,就这样一直筛,一直到筛子里面没有元素为止。
然后把一万以内的素数存到一个数组里,然后就开始尺取,如果尺取到的区间素数的和等于n,那就ans++,然后如果大于了,就left++,如果小于了就right++,注意的是这里不用考虑空区间,也就是left和right可以是相等的,因为素数本身也是一个满足条件的序列。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <list>
#include <map>
#define INF 0x3f3f3f3f
#define MID (l + r) >> 1
#define lsn rt << 1
#define rsn rt << 1 | 1
#define Lson lsn, l, mid
#define Rson rsn, mid + 1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
using namespace std;
typedef long long ll;
typedef vector<int>:: iterator VITer;
const int maxN = 1e5 + 5;
const int maxE = 1e4 +5;
const int N = 1e5;
int n;
int vis[maxN] = {0};
int prime[maxN] = {0}, cnt = 0;
void PRIme()
{
vis[0] = 1;
vis[1] = 1;
for(int i = 2; i <= N; i ++ )
{
if(!vis[i])
prime[++ cnt] = i;
for(int j = 1; j <= cnt; j ++)
{
if(i * prime[j] > N)
break;
vis[i * prime[j]] = 1;
if(i % prime[j] == 0)
break;
}
}
}
int main()
{
PRIme();
while(~scanf("%d", &n) && n)
{
int l = 1, r = 1;
int sum = 0, ans = 0;
while(l <= cnt && r <= cnt)
{
if(l > r)
{
r = l;
sum = 0;
}
if(sum == n)
{
ans ++;
sum -= prime[l];
l ++ ;
}
else if(sum > n)
{
sum -= prime[l];
l ++ ;
}
else
{
sum += prime[r];
r ++ ;
}
}
printf("%d\n", ans);
}
return 0;
}