Sum of consecutive prime numbers(离线计算)POJ 2739
作者:互联网
离线计算
在处理多个测试用例的过程中,可能会遇到这样一种情况:数据量较大,所有测试用例都采用同一运算,并且数据范围已知。
在这种情况下,为了提高计算时效,可以采用离线计算方法:预先计算出指定范围内的所有解,存入某个常量数组;以后每处理一个测试用例,直接从常量数组中引用相关数据就可以了,这样做避免了重复运算。
Description
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.由于每个测试用例都要计算素数,且素数上限为10000,因此
首先我们离线计算出【2,10001】内的所有素数,按照递增顺序存入数组prime【】。
2.依次处理每个测试用例。
设当前测试用例的输入为t,连续素数的和为cnt;cnt ==的表示数为ans.
3.采用双重循环计算n的表示数ans。
外循环:枚举所有可能的最小素数。
内循环,枚举有prime[i]开始的连续素数和cnt,如果cnt=t就ans++;
AC代码
#include<iostream>
using namespace std;
const int maxn = 10001;
bool is_prime[maxn];
int prime[maxn];
int main(){
for(int i = 2;i<maxn;i++){
is_prime[i] = 1;
}
for(int i = 2;i*i<maxn;i++){
if(is_prime[i]){
for(int j = i*i;j<maxn;j+=i){
is_prime[j] = 0;
}
}
}
int o = 0;
for(int i = 2;i<maxn;i++){
if(is_prime[i]){
prime[o] = i;
o++;
}
}
//cout<<o;
/*for(int i = 0;i<maxn&&prime[i];i++){
cout<<prime[i];
}*/
int t;
while(cin>>t&&t!=0){
int ans = 0;//和,表示个数
for(int i = 0;t>=prime[i];i++){
int cnt = 0;
for(int j = i;t>=prime[j];j++){
cnt += prime[j];
if(cnt==t){
//cout<<1;
ans++;
}
}
}
cout<<ans<<endl;
}
return 0;
}
标签:prime,cnt,int,Sum,离线,测试用例,representations,integer 来源: https://blog.csdn.net/qq_43063278/article/details/100060177