bzoj1257 数论分块
求\(\sum_{i=1}^n k \% i\)
其中1 <= n <= 1e9, 1 <= k <= 1e9
把取模拆开
\[k \% i = k - \lfloor\frac{k}{i}\rfloor * i
\]
注意到\(\lfloor\frac{k}{i}\rfloor\)总共有O(sqrt(k))种取值,可以数论分块。
代码:
#include <iostream>
using namespace std;
typedef long long LL;
LL sum(int l, int r) {
return (LL)(l + r) * (r - l + 1) / 2;
}
int main() {
int n, k;
cin >> n >> k;
LL ans = 0;
for (int i = 1, r; i <= k && i <= n; i = r + 1) {
int d = k / i;
r = k / d;
ans += d * sum(i, min(r, n));
}
ans = (LL)n * k - ans;
cout << ans << endl;
return 0;
}