和为N的连续正整数序列

  1. 我们给定一个数M,求连续的正整数序列的和为M。比如100=9+10+11+12+13+14+15+16=18+19+20+21+22。一我们为了处理方便设一个small=1,设一个big=2.。当所求的small到big的和大于M的时候,我们small++,去掉一个较小的数,当我们发现small到big的和小于M,我们big++,增加一个较大的树。直到small-bigm。根据题意至少知道small-big至少两数,所以small<(n+1)/2(偶数的时候为n/2,,奇数的时候向上取整,比如5=2+3,如果向下取整,small=2退出,那么就不会得出结果了);当small(n+1)/2的时候退出循环即可。当计算出一个连续正整数的序列之后,如果small(n+1)/2;,那么small++,big=small+1.接着重复计算过程,直到small==(n+1)/2。实现的代码如下:

  2. #include
    using namespace std;
    int sum(int begin, int end)
    {
    int sum = 0;
    for (int i = begin; i <= end; i++)
    {
    sum += i;
    }
    return sum;
    }
    void sum4N(int n)
    {
    int small = 1;
    int big = 2;
    while (small < (n + 1) / 2)
    {
    if (sum(small, big) > n)//当所求的small到big的和大于M的时候,我们small++,去掉一个较小的数
    {
    small++;
    }
    else if (sum(small, big) < n)//当我们发现small到big的和小于M,我们big++,增加一个较大的树
    {
    big++;
    }
    else
    {
    cout << small << “—” << big << " = " << n << endl;
    if (small < (n + 1) / 2)//当计算出一个连续正整数的序列之后,如果small(n+1)/2;,那么small++,big=small+1.接着重复计算过程,直到small==(n+1)/2。实现的代码如下:
    {
    small++;
    big = small + 1;
    }

    }
    

    }

}
int main()
{
sum4N(100);
cout << “------------” << endl;
sum4N(15);
cout << “------------” << endl;
sum4N(888);
cout << “------------” << endl;
system(“pause”);
return 0;
}
运行结果:如图所示:
在这里插入图片描述
结果非常完美。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值