C++ 实现连续正整数求和
该程序使用 C++ 代码实现将一个正整数分解为连续正整数的和。例如,78 可以表示为 18+19+20+21 或 25+26+27。
输入描述 一行一个正整数 n
输出描述 m 行,每行都是两个正整数,表示区间内容:
#include <iostream>
using namespace std;
int main() {
int n, cnt = 0;
cin >> n;
for (int i = 1; i * (i + 1) / 2 <= n; i++) {
int j = (-1 + sqrt(1 + 8 * (n - i * (i + 1) / 2))) / 2;
if (i * (i + 1) / 2 + j * (j + 1) / 2 == n) {
cnt++;
cout << i << ' ' << i + j << endl;
}
}
if (cnt == 0) cout << "No Solution" << endl;
return 0;
}
程序首先循环遍历可能的第一个数 i,并使用数学公式计算出对应的最后一个数 j,判断是否满足条件。如果满足,则输出 i 和 j,并计数。如果遍历完所有可能的 i 后仍然没有找到解,则输出 "No Solution"。
原文地址: https://www.cveoy.top/t/topic/opVy 著作权归作者所有。请勿转载和采集!