hdu2058 The sum problem _数论

本文探讨了给定序列1到N中所有可能的子序列,使得子序列的和等于给定值M的问题。通过利用等差数列的性质,采用枚举方法找到所有符合条件的子序列,并给出了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The sum problem

 

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23781    Accepted Submission(s): 7068

 

 

Problem Description

Given a sequence 1,2,3,......N, your job is to calculate all the possible sub-sequences that the sum of the sub-sequence is M.

 

 

Input

Input contains multiple test cases. each case contains two integers N, M( 1 <= N, M <= 1000000000).input ends with N = M = 0.

 

 

Output

For each test case, print all the possible sub-sequence that its sum is M.The format is show in the sample below.print a blank line after each test case.

 

 

Sample Input


 

20 10 50 30 0 0

 

 

Sample Output


 

[1,4] [10,10] [4,8] [6,9] [9,11] [30,30]

 

 

思路:利用等差数列的性质  末项an=a1+(n-1)*d;  n项和sn=(a1+an)*n/2=a1*n+n*(n-1)*d/2;
在本题中,d=1, sn=m; 即有m=a1*n+n*(n-1)/2;
假设首项是1,我们代入m=a1*n+n*(n-1)/2,则有n(n+1)=2m(n是项数的个数)。
所以有n*(n+1)=2m>n*n,即n<sqrt(2m); 也就是说项数最多的情况也只有sqrt(2m)。这也就是说,
假设M给的是10的9次方,最大的答案区间撑死也只有46000左右的长度。也就是2的10次的算术平方根。
(以上的'n'不是题目中的n,以上的'm'为题目中的m)
 
那么我们枚举1---sqrt(2m),枚举的是项数的个数(即数列区间长度); 
m知道了,长度知道了,那么可以解出首项;(即解方程m=a1*n+n*(n-1)/2;) 
又这个数列的每一项必定是个正整数,那么如果算出来的首项正好是个正整数,那么就是个答案,

区间就是【算出来的整数,整数+长度-1】输出即可。

 

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;

int main()
{
	int n,m;
	while(cin>>n>>m,n||m)
	{
		double a1,flag;
		for(int i=floor(sqrt(2*m));i>0;i--) //i是区间长度,即子数列项数个数 
		{
			a1=(1.0*2*m/i-i+1)/2; //解方程求子数列首项 
			flag=a1-floor(a1);
			if(flag==0&&a1<=m&&a1+i-1<=m)printf("[%.lf,%.lf]\n",a1,a1+i-1);
		}
		printf("\n");
	}
	return 0;
} 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值