#include <iostream> #include <cmath> #include <vector> using namespace std; struct node{ int left; int right; }; int main() { long N, M; long long sum = 0; vector<node> nodes; while (cin >> N >> M) { if (N == 0 && M == 0) break; for (long n = N; n >=1; n--) { if ((2*M-n*n+n)%(2*n)!=0) continue; long long a1 = (2 * M - n*n + n) / (2 * n); long long an = a1 + n - 1; if (a1 >= 1 && a1 <= N && an >= 1 && an <= N && a1 <= an) { //node node; //node.left = a1; //node.right = an; //nodes.push_back(node); cout << "[" << a1 << "," << an << "]" << endl; } } //for (node node : nodes) //{ // cout << "[" << node.left << "," << node.right << "]" << endl; //} cout << endl; } return 0; }
超時node
a1 = kios
an = k + n - 1spa
M = n*(2k+n-1)/2code
解的blog
k = M/n - (n-1)/2,這個不能這樣寫,要寫在一塊兒ci
(2M-n*n-n)/(2*n)。不然對於30/4 - 3/2,會忽略這樣的結果,若是先通分固然也就能夠。io
超時class
利用a1>=1這個條件能夠減小循環次數stream
2M - n*n >n循環
2M > n*n - n>n*n
sqrt(2M)>n
#include <iostream> #include <cmath> #include <vector> using namespace std; struct node{ int left; int right; }; int main() { long N, M; long long sum = 0; vector<node> nodes; while (cin >> N >> M) { if (N == 0 && M == 0) break; for (long n = sqrt(2*M); n >=1; n--) { if ((2*M-n*n+n)%(2*n)!=0) continue; long a1 = (2 * M - n*n + n) / (2 * n); long an = a1 + n - 1; if (a1 >= 1 && a1 <= N && an >= 1 && an <= N && a1 <= an) { //node node; //node.left = a1; //node.right = an; //nodes.push_back(node); cout << "[" << a1 << "," << an << "]" << endl; } } //for (node node : nodes) //{ // cout << "[" << node.left << "," << node.right << "]" << endl; //} cout << endl; } return 0; }