算法学习十三----和为n连续正数序列

本文介绍了一种算法,用于找出所有连续正数序列,这些序列的和等于给定的正整数n。通过使用辅助空间来保存序列,并通过调整序列的起始和结束点来迭代地找到所有可能的序列。

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

题目:输入一个正数n,输出所有和为n连续正数序列。
例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。
算法思路
采用辅助空间保存序列。用i从1开始做起点,j从i+1开始,直到i等于(1+n)/2
1、如果i-j的和等于n,则输出序列
2、如果i-j的和大于n,则将序列清空
3、如果i-j的和小于n,则将j假如到序列中

算法伪代码:

void CotinuousSeq(int n)
     initialize a sequence

     for i <- 1 to (1+n)/2
          push first element

          for j <- i+1 to (1+n)/2
               if j+sum(tvec) <= n
                    then push into sequence

               if sum(ivec) = n
                    then print the sequence and clear the sequence
               else clear the sequence

C++实现

void CotinuousSeq(int n)
{
    //initialize a sequence
    vector<int> tvec;

    //for i <- 1 to (1+n)/2
    for(int i = 1; i <= (1+n)/2; ++i)
    {
        //push first element
        tvec.push_back(i);

        //for j <- i+1 to (1+n)/2
        for(int j = i+1; j <= (1+n)/2; ++j)
        {
            //if j+sum(tvec) <= n
            if((j + sum(tvec)) <= n)
            {
                //then push into sequence
                tvec.push_back(j);

                //if sum(ivec) = n
                if(sum(tvec) == n)
                {
                    //then print the sequence and clear the sequence
                    print(tvec);
                    tvec.clear();
                    break;
                }
            }
            else
            {
                //else clear the sequence
                tvec.clear();
                break;
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值