尺取法

本文解析了尺取法在解决关于连续素数表示整数问题的方法,介绍了其适用场景、区间端点推进策略及结束条件,通过实例演示如何编写一个计算给定正整数由连续素数表示方式数量的程序。

尺取法

尺取法:通常是对数组保存一对下标,即所选取的区间的左右端点,然后根据实际情况不断地推进区间左右端点以得出答案。
使用尺取法时应清楚以下四点:
1、 什么情况下能使用尺取法?
2、何时推进区间的端点?
3、如何推进区间的端点?
4、何时结束区间的枚举?
尺取法通常适用于选取区间有一定规律,或者说所选取的区间有一定的变化趋势的情况,通俗地说,在对所选取区间进行判断之后,我们可以明确如何进一步有方向地推进区间端点以求解满足条件的区间,如果已经判断了目前所选取的区间,但却无法确定所要求解的区间如何进一步得到根据其端点得到,那么尺取法便是不可行的。
首先,明确题目所需要求解的量之后,区间左右端点一般从最整个数组的起点开始,之后判断区间是否符合条件在根据实际情况变化区间的端点求解答案。

eg1:

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
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn=1e6+10;
int vis[maxn];
int s[maxn];
int k=0;
void init()//素数打表
{
	memset(vis,1,sizeof(vis));
	vis[0]=0;
	vis[1]=0;
	for(int i=2;i<=maxn;i++)
	{
		if(vis[i])
		{
			s[k++]=i;
			for(int j=2*i;j<=maxn;j+=i) vis[j]=0;
		}
	}
}
int main()
{
	init();
	int x;
	while(~scanf("%d",&x)&&x)
	{
		int sum=0;//和
		int ans=0;//个数
		int l=0,r=0;//左端点和右端点
		while(1)
		{
			while(sum<x&&s[r]<=x)//右端点右移动
			{
				sum+=s[r++];
			}
			if(sum<x) break;//结束
			else if(sum>x)//通过右移左端点减少sum
			{
				sum-=s[l++];
			}
			else if(sum==x)//相等时,个数加一.左端点右移减少sum后右移右端点,再次构建x值
			{
				ans++;
				sum-=s[l++];
			}
		}
		printf("%d\n",ans);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值