您的位置:首页 > 其它

51nod 1138 连续整数的和(数学)

2015-01-11 21:42 225 查看
题目描述:

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1138

给出一个正整数N,将N写为若干个连续数字和的形式(长度 >= 2)。例如N = 15,可以写为1 + 2 + 3 + 4 + 5,也可以写为4 + 5 + 6,或7 + 8。如果不能写为若干个连续整数的和,则输出No Solution。

Input
输入1个数N(3 <= N <= 10^9)。


OutPut
输出连续整数中的第1个数,如果有多个按照递增序排列,如果不能分解为若干个连续整数的和,则输出No Solution。


Input示例

15


Output示例

1
4
7

题目分析:
此题有很多数学技巧,我是在《短码之美》上学到的解法,请大家看《短码之美》。

AC代码:
/**
*@xiaoran
*/
#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<cstdlib>
#include<cctype>
#include<cmath>
#define LL long long
using namespace std;
int main()
{
int n;
while(cin>>n){
stack<int> st;
int i=1;
while(n-i>1){
n-=i++;
if(n%i==0){
//cout<<n/i<<endl;
st.push(n/i);
}
}
if(st.empty()){
cout<<"No Solution"<<endl;
continue;
}
while(!st.empty()){
cout<<st.top()<<endl;
st.pop();
}
}
return 0;
}

附:求组成n的连续序列的个数,和这些序列的组成。

/**
*连续数的和的个数,短码之美题
*并求出这些组合
*/
#include<iostream>
using namespace std;
void print(int n){//打印这些序列组合
int i=0,s=n;
while(n-i>0){
n-=i++;
if(n%i==0){
cout<<s<<"=";
int k,k1;
for(k=0,k1=n/i;k<i-1;k++,k1++){
cout<<k1<<"+";
}
cout<<k1<<endl;
}
}
}

int main()
{
int n;
while(cin>>n){
int sum=0,i=0;
print(n);
while(n>0){
n-=++i;
n%i||sum++;
}
cout<<sum<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: