例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以输出3个连续序列1-5、4-6和7-8。
#include#include using std::cin;using std::cout;using std::endl;using std::vector;vector< vector > consecaddend(int n){ vector< vector > vec; vector iv; int i, j; //i是序列的长度,最大不超过sqrt(2n) //当n/i == i/2时应判断:如果i是奇数则停止循环,否则会得到以0开头的序列 //如:10/4 == 10/5 == 4/2 == 5/2 == 2 (感谢指正) for (i = 2; ((j = n/i) > i/2) || (j == i/2) && (i%2 == 0); i++) if (i%2) { //i为奇数,仅当n能被i整除时存在这样的序列 if (n%i == 0) { j -= i/2; for (int k = 0; k != i; ++k) iv.push_back(j++); vec.push_back(iv); iv.clear(); } } else { //i为偶数,仅当n/i小数部分为0.5时存在这样的序列 if (n%i != 0 && 2*n%i == 0) { j -= i/2 - 1; for (int k = 0; k != i; ++k) iv.push_back(j++); vec.push_back(iv); iv.clear(); } } return vec;}int main(void){ int x; vector< vector > v; while (cin >> x) { v = consecaddend(x); for(vector< vector >::iterator viter = v.begin(); viter != v.end(); ++viter) { for(vector ::iterator iter = viter->begin(); iter != viter->end(); ++iter) cout << *iter << " "; cout << endl; } v.clear(); } return 0;}