引理一
$$\forall a,b,c\in\mathbb{Z},\left\lfloor\frac{a}{bc}\right\rfloor=\left\lfloor\frac{\left\lfloor\frac{a}{b}\right\rfloor}{c}\right\rfloor$$
略证:
\begin{split} &\frac{a}{b}=\left\lfloor\frac{a}{b}\right\rfloor+r(0\leq r<1)\\ \Rightarrow &\left\lfloor\frac{a}{bc}\right\rfloor =\left\lfloor\frac{a}{b}\cdot\frac{1}{c}\right\rfloor =\left\lfloor \frac{1}{c}\left(\left\lfloor\frac{a}{b}\right\rfloor+r\right)\right\rfloor =\left\lfloor \frac{\left\lfloor\frac{a}{b}\right\rfloor}{c} +\frac{r}{c}\right\rfloor =\left\lfloor \frac{\left\lfloor\frac{a}{b}\right\rfloor}{c}\right\rfloor\\ &&\square \end{split}
引理二
$$\forall n \in N, \left|\left\{ \lfloor \frac{n}{d} \rfloor \mid d \in N \right\}\right| \leq \lfloor 2\sqrt{n} \rfloor$$
$|V|$表示集合$V$的元素个数
略证:
对于$d \leq \left \lfloor \sqrt{n} \right \rfloor$,$\left \lfloor \frac{n}{d} \right \rfloor$有$\left \lfloor \sqrt{n} \right \rfloor$种取值.
对于$d \geq \left \lfloor \sqrt{n} \right \rfloor$,有$\left \lfloor \frac{n}{d} \right \rfloor \leq \left \lfloor \sqrt{n} \right \rfloor$,也只有$\left \lfloor \sqrt{n} \right \rfloor$种取值.
数论分块
数论分块的过程大概如下:考虑含有$\left \lfloor \frac{n}{i} \right \rfloor$的求和式子($n$为常数)
对于任意一个$i$($i \leq n$),我们需要找到一个最大的$j$($i \leq j \leq n$),使得$\left \lfloor \frac{n}{i} \right \rfloor = \left \lfloor \frac{n}{i} \right \rfloor$.
那么$j = \left \lfloor \frac{n}{\left \lfloor \frac{n}{i} \right \rfloor} \right \rfloor$.
略证:
\begin{split} &\left\lfloor\frac{n}{i}\right\rfloor \leq \frac{n}{i}\\ \Rightarrow &\left\lfloor\frac{n}{ \left\lfloor\frac{n}{i}\right\rfloor }\right\rfloor \geq \left\lfloor\frac{n}{ \frac{n}{i} }\right\rfloor = \left\lfloor i \right\rfloor=i \\ \Rightarrow &i\leq \left\lfloor\frac{n}{ \left\lfloor\frac{n}{i}\right\rfloor }\right\rfloor\\ &&\square \end{split}
即$j = \left \lfloor \frac{n}{\left \lfloor \frac{n}{i} \right \rfloor} \right \rfloor$.
利用上述结论,我们每次以$[i,j]$为一块,分块求和即可.
实现
快速计算$\sum \left \lfloor \frac{n}{i} \right \rfloor$的方法:
1 for(int l = 1, r; l <= n;l = r+1) 2 { 3 r = n / (n / l); 4 ans += (r-l+1) * (n / l); 5 printf("%d %d %d %d\n", l, r, n/l, n/r); 6 }
参考链接:https://oi-wiki.org/math/mobius/