Official

D - Staircase Sequences Editorial by en_translator


The sum of sequence \([A, A + 1, \dots, B - 1, B]\) is \(\dfrac{(A + B)(B - A + 1)}{2}\) (which can be understood by adding \([B, B-1, \dots, A + 1, A]\) to each element).

Therefore, this problem is equivalent to finding the number of integer solutions of

\[ (A + B)(B - A + 1) = 2N \quad (A ≤ B). \]

Here, \(A + B, B - A + 1\) are both divisors of \(2N\) because they are both integers.
Now, enumerate the ways of decomposing into two positive integers like \(2N=x \times y\) and solve

\[ \begin{cases} A + B = x\\ B - A + 1 = y\\ \end{cases} \]

so that we can find the number of integer solutions.
Its solution is
\(A = (x - y + 1)/2,\ B = (x + y - 1)/2\)
if the parities of \(x\) and \(y\) differs; otherwise, there are no such integer solutions.

Therefore, the answer is the number of ways to decompose \(2N\) into two integers of different parities.
Since the divisors of \(2N\) can be enumerated in a time complexity of \(O(\sqrt N)\), the problem can be solved in a total of \(O(\sqrt N)\) time.

Also, since \(2N\) has at least one \(2\)’s as its prime factor, either, but not both, of \(x\) and \(y\) has \(2\) as its divisor.
Therefore, the answer is (number of divisors of \(M\))\({}\times 2\), where \(M =\) (\(N\) divided by two repeatedly until its it indivisible by \(2\)).

Sample Code (C++)

#include <iostream>
#include <cmath>
using namespace std;
using ll = int64_t;

int main(){ ll N;
    cin >> N;
    while(N % 2 == 0) N /= 2;
    ll sq = sqrt(N), ans = 0;
    for(ll i = 1; i <= sq; i++) if(N % i == 0) ans += 2;
    if(sq * sq == N) ans--;
    cout << ans * 2 << endl;
}

Sample Code (Python)

N = int(input())
while N % 2 == 0:
    N //= 2
sq = int(N ** 0.5)
ans = sum(N % i == 0 for i in range(1, sq + 1)) * 2 - (sq * sq == N)
print(ans * 2)

posted:
last update: