Olympiad in Informatics

Universal OJ: #42 [Tsinghua Training Camp 2014] Sum — Solution

Main Idea

This transformation is really brilliant...

First, we transform \((-1)^b\). It turns out it can be turned into something number-theoretic: \((-1)^b = 1 - 2(b \bmod 2)\), so we can massage the expression a bit:

\[ \begin{aligned} & \sum_{i = 1}^n 1 - 2(\lfloor i \sqrt r \rfloor \bmod 2) \\ =& n -2\sum_{i = 1}^n \lfloor i \sqrt r \rfloor - 2 \lfloor \frac{i \sqrt r}{2} \rfloor \end{aligned} \]

Consider computing \(\sum_{i = 1}^n \lfloor i \sqrt r \rfloor\). Since \(\sqrt r\) is irrational, which is pretty annoying, we can try to wrap it up in Euclidean-like algorithm form, starting with \(a = 1, b = 0, c = 1\):

\[ \begin{aligned} & \sum_{i = 1}^n \lfloor i \sqrt r \rfloor \\ =& \sum_{i = 1}^n \lfloor i \cdot \frac{a \sqrt r + b}{c} \rfloor \end{aligned} \]

What this amounts to is counting the lattice points in the lower triangle formed by the line with this slope and the \(x\) axis. We split into cases on the slope.

If \(k = \frac{a \sqrt r + b}{c} > 1\), we can directly use algebra:

\[ \begin{aligned} & \sum_{i = 1}^n \lfloor i \cdot \frac{a \sqrt r + b}{c} \rfloor \\ =& \sum_{i = 1}^n \lfloor i \cdot (\frac{a \sqrt r + b}{c} - \lfloor \frac{a \sqrt r + b}{c} \rfloor) \rfloor + i \lfloor \frac{a \sqrt r + b}{c} \rfloor \end{aligned} \]

If not, we can tilt the line over (reflect the line about \(y = x\)), then subtract the number of points in the lower triangle from the area of the rectangle. The new slope is \(\frac{1}{\frac{a\sqrt r + b}{c}} = \frac{ac\sqrt r - bc}{a^2 r - b^2}\), and the projection of the rectangle onto the \(x\) axis is \(\frac{a\sqrt r + b}{c} \cdot n\). With everything in place, just apply the Euclidean-like algorithm directly.

Code

// UOJ42.cpp
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

ll T, n, r;
double spart;

ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }

ll calc(ll a, ll b, ll c, ll n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return (a * spart + b) / c;
    ll d = gcd(gcd(a, b), c);
    a /= d, b /= d, c /= d;
    ll verdict = (a * spart + b) / c;
    if (verdict == 0)
    {
        // transform the axis system;
        ll rect_area = ll((a * spart + b) / c * n) * n;
        return rect_area - calc(a * c, -c * b, a * a * r - b * b, (a * spart + b) / c * n);
    }
    else
        return calc(a, b - c * verdict, c, n)  + verdict * n * (n + 1) / 2;
}

int main()
{
    scanf("%lld", &T);
    while (T--)
    {
        scanf("%lld%lld", &n, &r);
        spart = sqrt(r);
        if (ll(spart) * ll(spart) == r)
        {
            // calc;
            if (ll(spart) % 2 == 0)
                printf("%lld\n", n);
            else
                printf("%lld\n", n - 2 * ((n + 1) >> 1));
            continue;
        }
        printf("%lld\n", n - 2LL * calc(1, 0, 1, n) + 4LL * calc(1, 0, 2, n));
    }
    return 0;
}