类欧几里得算法
快速求解
\[f(a,b,c,n)=\sum_{i=0}^n\left \lfloor \frac{ai+b}{c} \right \rfloor
\]
若 \(\max(a,b)\ge c\)
\[设 s_0(n)=n+1,s_1(n)=\frac{n(n+1)}{2},s_2(n)=\frac{n(n+1)(2n+1)}{6}
\sum_{i=0}^n\left \lfloor \frac{ai+b}{c} \right \rfloor=\sum_{i=0}^n\left \lfloor \frac{ai\bmod c+ic\lfloor\frac{a}{c}\rfloor+b\bmod c+c\lfloor\frac{b}{c}\rfloor}{c} \right \rfloor\\
=s_1(n)\lfloor\frac{a}{c}\rfloor+s_0(n)\lfloor\frac{b}{c}\rfloor+f(a\bmod c,b\bmod c,c)
\]
否则
\[\sum_{i=0}^n\sum_{j=0}^{\lfloor \frac{ai+b}{c}\ \rfloor-1}1\\
令 m=\left\lfloor \frac{an+b}{c}\ \right\rfloor\\
\sum_{j=0}^{m-1}\sum_{i=0}^n\left[j<\left \lfloor \frac{ai+b}{c} \right \rfloor\right]\\
\left[j<\left \lfloor \frac{ai+b}{c} \right \rfloor\right]\iff j+1\le \frac{ai+b}{c}\iff ai\ge j+c-b\\
\iff ai>j+c-b-1
\iff i>\left \lfloor \frac{jc+c-b-1}{a} \right \rfloor\\
\sum_{j=0}^{m-1}\sum_{i=0}^n\left[j<\left \lfloor \frac{ai+b}{c} \right \rfloor\right]=\sum_{j=0}^{m-1}\sum_{i=0}^n\left[i>\left \lfloor \frac{jc+c-b-1}{a} \right \rfloor\right]\\
\sum_{j=0}^{m-1}(n-\left\lfloor \frac{jc+c-b-1}{a} \right\rfloor)\\
=nm-f(c,c-b-1,a,m-1)\\
f(0,b,c,n)=s_0(n)\left\lfloor\frac{b}{c}\right\rfloor
\]
作为其应用更少的分支,有以下结论:
\[g(a,b,c,n)=\sum_{i=0}^ni\left \lfloor \frac{ai+b}{c} \right \rfloor\\
h(a,b,c,n)=\sum_{i=0}^n\left \lfloor \frac{ai+b}{c} \right \rfloor^2\\
g(a,b,c,n)=g(a\bmod c,b\bmod c,c,n)+\left \lfloor \frac{a}{c} \right \rfloor s_2(n)+\left \lfloor \frac{b}{c} \right \rfloor s_1(n)\\
g(a,b,c,n)=\frac{mn(n+1)-h(c,c-b-1,a,m-1)-f(c,c-b-1,a,m-1)}{2}\\
h(a,b,c,n)=h(a\bmod c,b\bmod c,c,n)+2\left \lfloor \frac{b}{c} \right \rfloor f(a\bmod c,b\bmod c,c,n)+2\left \lfloor \frac{a}{c} \right \rfloor g(a\bmod c,b\bmod c,c,n)+\left \lfloor \frac{a}{c} \right \rfloor^2s_2(n)+\left \lfloor \frac{b}{c} \right \rfloor^2s_0(n)+2\left \lfloor \frac{a}{c} \right \rfloor\left \lfloor \frac{b}{c} \right \rfloor s_1(n)\\
h(a,b,c,n)=nm(m+1)-2g(c,c-b-1,a,m)-2f(c,c-b-1,a,m)-f(a,b,c,n)
\]
YJX AK IOI