「loj - 6724」「CodePlus #7」同余方程
link。
由 CRT,我们只考虑模奇素数 \(p\) 的情况。
利用勒让德符号帮助计数(此处记 \(\left(\frac{0}{p}\right) = 0\)):
\[\begin{aligned}
ans &= \sum_{i=0}^{p-1}(\left(\frac{i}{p}\right) + 1)(\left(\frac{x-i}{p}\right) + 1) \\
&= \sum_{i=0}^{p-1}\left(\frac{i}{p}\right)\left(\frac{x-i}{p}\right) + 2\sum_{i=0}^{p-1}\left(\frac{i}{p}\right) + p
\end{aligned}
\]
由于勒让德符号的一些性质,可得 \(\left(\frac{i}{p}\right)\left(\frac{x-i}{p}\right) = \left(\frac{i(x-i)}{p}\right)\),且 \(\sum_{i=0}^{p-1}\left(\frac{i}{p}\right) = 0\):
\[\begin{aligned}
ans &= \sum_{i=\color{red}{1}}^{p-1}\left(\frac{i(x-i)}{p}\right) + p \\
&= \sum_{i=1}^{p-1}\left(\frac{\frac{x}{i} - 1}{p}\right) + p
\end{aligned}
\]
当 \(x = 0\) 时,\(ans = (p-1)\times\left(\frac{-1}{p}\right)+p=(p-1)\times(-1)^{\frac{p-1}{2}}+p\)。
当 \(x\neq 0\) 时,\(ans = \sum_{i=0}^{p-1}\left(\frac{i}{p}\right) - \left(\frac{-1}{p}\right) + p = (-1)^{\frac{p+1}{2}} + p\)。
更一般的情况可见 https://blog.csdn.net/qq_39972971/article/details/106379811 。