推式子:
$$
\begin {aligned}
& \sum _ {i = 1} ^ n \sum _ {j = 1} ^ m (n \bmod i) (m \bmod j) [i \neq j] \\
= & (\sum _ {i = 1} ^ n n \bmod i) (\sum _ {j = 1} ^ m m \bmod j) - \sum _ {i = 1} ^ n (n \bmod i)(m \bmod i) \\
= & (\sum _ {i = 1} ^ n n - i \left \lfloor \frac n i \right \rfloor) (\sum _ {j = 1} ^ m m - j \left \lfloor \frac m j \right \rfloor) - \sum _ {i = 1} ^ n (n - i \left \lfloor \frac n i \right \rfloor)(m - i\left \lfloor \frac m i \right \rfloor) \\
= & (n ^ 2 - \sum _ {i = 1} ^ n i \left \lfloor \frac n i \right \rfloor) (m ^ 2 - \sum _ {j = 1} ^ m j \left \lfloor \frac m j \right \rfloor) - \sum _ {i = 1} ^ n (nm - mi \left \lfloor \frac n i \right \rfloor - ni \left \lfloor \frac m i \right \rfloor + i ^ 2 \left \lfloor \frac n i \right \rfloor \left \lfloor \frac m i \right \rfloor) \\
\end {aligned}
$$
关于计算前缀平方和,有公式:
$$
\sum _ {i = 1} ^ k i ^ 2 = \frac {k (k + 1) (2k + 1)} 6
$$
整除分块可以在 $O(\sqrt n)$ 的时间内完成计算。
查看代码
1 |
|