1. 程式人生 > >演算法 - 求和為n的連續正整數序列(C++)

演算法 - 求和為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. */

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!希望你也加入到我們人工智慧的隊伍中來!http://www.captainbed.net