Sum of Consecutive Prime Numbers POJ - 2739(线性欧拉筛+尺取法)
題意:
一些正整數可以由一個或多個連續質數的總和表示。給定一個的正整數n,問滿足條件的有多少種情況?
題目:
Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2+3+5+7+11+13, 11+13+17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime
numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20.
Your mission is to write a program that reports the number of representations for the given positive integer.
Input
The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero.
Output
The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output.
Sample Input
2
3
17
41
20
666
12
53
0
Sample Output
1
1
2
3
0
0
1
2
分析:
1.將 2 至 10000 內的素數存入一個數組;
2.對于每一個給定的數,從左向右遍歷數組,根據連續素數的和的大小不斷的增減元素,直到找到一個個解。
AC模板:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int M=1e4+10; int n,k,r,l,ans,mi; int dp[M],book[M]; void init() {k=0;/** for(int i=2; i<M; i++){if(!book[i]){dp[k++]=i;for(int j=i*2; j<M; j+=i)book[j]=1;}}*/for(int i=2;i<M;i++){if(!book[i])dp[k++]=i;for(int j=0;j<k&&i*dp[j]<M;j++){book[i*dp[j]]=1;if(i%dp[j]==0)break;}}} int solve(int x) {ans=0;for(int i=0; i<k&&dp[i]<=x; i++){l=i,mi=0;while(mi<x&&l<k){mi+=dp[l++];}if(mi==x)ans++;}return ans; } int main() {init();while(~scanf("%d",&n)&&n){printf("%d\n",solve(n));}return 0; }備戰ccpc分站賽ing ,題目分析簡略,見諒,轉載請注明出處。。。。。
總結
以上是生活随笔為你收集整理的Sum of Consecutive Prime Numbers POJ - 2739(线性欧拉筛+尺取法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Bound Found POJ - 25
- 下一篇: 减肥午餐吃什么