Luo Gu P1147 consecutive natural numbers and explanations enumeration

Topic links: https://www.luogu.com.cn/problem/P1147

Topic effect:
to give you a number \ (M \) , how much demand there is for continuous natural number is the sum of \ (M \) , the output of the first term and last term this column to the successive natural numbers.

Problem-solving ideas:
the number of elements in the enumeration of the number of consecutive natural \ (i \) .
Because the more natural logarithm of the number of elements in a row, the first term is smaller, so we from \ (M \) to \ (2 \) the number of enumeration \ (i \) .
In the case of a known number of elements, we set up the first item is \ (A \) , then:

\[a+a+1+ \dots + a+i-1 = M\]

\[\Rightarrow a \times i + 1+2+ \dots +i-1 = M\]

\[\Rightarrow a \times i + \frac{i \times (i-1)}2 = M\]

\[\Rightarrow a = \frac{M-\frac{i(i-1)}2}{i}\]

Denominator can molecule divisible by the above formula, and the calculated \ (A> 0 \) , then find a continuous natural logarithm, which is the first item \ (A \) , the last term of \ (a + i-1 \) .

It should be noted that, because \ (M \ Le 2 \ Times 10 ^ 6 \) , so \ (i \ times i / 2 \) may exceed int, so there are two solutions when dealing with:

  • One is open long long;
  • Another is to first determine \ ((i-1) / 2> m / i \) is satisfied, if the establishment of the first item description \ (\ 0 Le \) , skip this step towards a smaller interval to judge .

Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
int m;
int main() {
    cin >> m;
    for (int i = m; i > 1; i --) {
        if ((i-1)/2 > m/i) continue;
        if ( (2*m-i*(i-1)) % (2*i) == 0 ) {
            int a = (2*m-i*(i-1))/(2*i);
            int b = a + i - 1;
            if (a > 0)
                cout << a << " " << b << endl;
        }
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/quanjun/p/12006300.html