算法 - 求和为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.
*/
上一篇:读《JavaScript DOM编程艺术》


下一篇:VS2010 VS2012 如何连接Oracle 11g数据库