BZOJ1257: [CQOI2007] Sum of Remainders — Solution
A Godlike Approach and Proof
The expression in this problem can be simplified to:
\[ nk-\sum_{i=1}^{n} \lfloor \frac{k}{i} \rfloor * i \]
The first part is just a product. For the second part, intuition tells us that \(\lfloor \frac{k}{i} \rfloor\) stays equal over a run of consecutive \(i\), that is, it is piecewise. The sum of each piece can be computed directly as an arithmetic series. Let's look into the left and right endpoints of each piece. Suppose the target interval is \([i,?]\); then the value over this interval must be \(\lfloor \frac{k}{i} \rfloor\), and solving backwards, the right endpoint is \( \lfloor \frac{k}{\lfloor \frac{k}{i} \rfloor} \rfloor \). It can be proved that the right endpoint is greater than or equal to the left endpoint. Then just sum the arithmetic series.
Code
// BZ1257.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll n, k;
int main()
{
scanf("%lld%lld", &n, &k);
ll ans = n * k, gx;
for (int x = 1; x <= n; x = gx + 1)
{
gx = (k / x) ? min(k / (k / x), n) : n;
// x ~ gx same;
ans -= (k / x) * (gx - x + 1) * (gx + x) / 2;
}
printf("%lld", ans);
return 0;
}