Luogu P2261 [CQOI2007]余数求和
\[ans = \sum\limits_{i=1}^{n} k \bmod i \\ = \sum\limits_{i=1}^{n} k - \lfloor \frac{k}{i} \rfloor * i \\ = n*k-\sum\limits_{i=1}^{n}\lfloor \frac{k}{i} \rfloor * i
\]
\(i \le \sqrt k\)时,\(\lfloor \frac{k}{i} \rfloor\)最多有\(\sqrt k\)种不同取值;
\(i > \sqrt k\)时,\(\lfloor \frac{k}{i} \rfloor\)的取值范围小于\(\sqrt k\),最多也有\(\sqrt k\)种;
所以一共最多只有\(2\sqrt k\)种,可以用数论分块解决。
注意\(\lfloor \dfrac{k}{\lfloor \frac{k}{i}\rfloor}\rfloor\)可能\(>n\),要取\(min\)。
code
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#define MogeKo qwq
using namespace std;
long long n,k,ans;
int main() {
scanf("%lld%lld",&n,&k);
ans = n*k;
for(long long i = 1,r; i <= n; i = r+1) {
if(i > k) break;
r = min(k/(k/i),n);
ans -= (k/i)*(r-i+1)*(i+r)/2;
}
printf("%lld",ans);
return 0;
}