算法 - 求和为n的连续正整数序列(C++)

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

/*
 * 求和为n的连续正整数序列 - C++ - by Chimomo
 *
 * 题目: 输入一个正整数n,输出所有和为n的连续正整数序列。例如:输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。
 *
 * Answer:
 *
 * Suppose n = i+(i+1)+...+(j-1)+j,
 * then n = (i+j)(j-i+1)/2 = (j*j-i*i+i+j)/2
 * => j^2+j+(i-i^2-2n) = 0
 * => j = (sqrt(1-4(i-i^2-2n))-1)/2
 * => j = (sqrt(4i^2+8n-4i+1)-1)/2.
 *
 * We know 1 <= i < j <= n/2+1, so for each i in [1,n/2], do this arithmetic to check if there is a integer answer.
 *
 * Note: 二次函数 ax^2+bx+c=0 的求根公式为: x = (-b±sqrt(b^2-4ac))/2a。
 */

#include <iostream>
#include <cassert>
#include <stack>
#include <math.h>

using namespace std;

int FindConsecutiveSequence(int n) {
    int count = 0;

    for (int i = 1; i <= n / 2; i++) {
        double sqroot = sqrt(4 * i * i + 8 * n - 4 * i + 1);
        int floor = sqroot;

        if (sqroot == floor) {
            cout << i << "-" << (sqroot - 1) / 2 << endl;
            count++;
        }
    }

    return count;
}

int main() {
    int count = FindConsecutiveSequence(15);
    cout << "Totally " << count << " sequences found." << endl;
    return 0;
}

// Output:
/*
1-5
4-6
7-8
Totally 3 sequences found.

*/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值