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

题目描述:

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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值