您的位置:首页 > 其它

POJ 2739 Sum of Consecutive Prime Numbers(数学,素数打表)

2016-02-15 01:11 459 查看
Sum of Consecutive Prime Numbers

Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 22069Accepted: 12079
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
23
1741
66620
12
053

Sample Output
11
32
0
20
1


题意:给出一个数n,问n可以与几种形式的连续的素数相加相等。

题解:题目给出的范围是10000,先将10000内的素数打表判断出来,然后按序存入一个数组,10000内的素数有1229个。 最后遍历从1~n之间的素数的子区间,判断有多少个区间和与n相等。

代码如下:

#include<cstdio>
#include<cstring>
#include<cmath>
int a[10010]={1,1},cnt[2000],k;

void primetable()
{
	int i,j;
	for(i=2;i<=100;++i)
	{
		if(a[i])
			continue;
		for(j=i*i;j<10010;j+=i)
			a[j]=1;
	}
	k=0;
	for(i=2;i<=10000;++i)
	{
		if(!a[i])
			cnt[k++]=i;
	}
}

int main()
{
	primetable();
	int n,i,j,ans,sum;
	while(scanf("%d",&n)&&n)//下面的部分,可以尺取法写,不过这里的O(n^2)的算法能AC了
	{
		ans=0;
		for(i=0;i<k;++i)
		{
			sum=0;
			if(cnt[i]>n)
				break;
			for(j=i;;j++)
			{
				sum+=cnt[j];
				if(sum>n)
					break;
				if(sum==n)
				{
					ans++;
					break;
				}
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


刚刚想了一下,查找的部分可以用尺取法写,这样查找的时间复杂度就降到了O(n),尺取法的代码就不写了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: