对于求和式 $f(a,b,c,n)=sum_{i=0}^n lfloor frac{ai+b}{c} floor$
当 $a geq c$ 或 $b geq c$ 时,设 $a'=a ; mod ; c$,$b'=b ; mod ; c$,有
$$egin{align*} f(a,b,c,n) = & sum_{i=0}^n ; lfloor frac{ai+b}{c} floor \ = & sum_{i=0}^n ; lfloor frac{a'i+b'}{c} floor + lfloor frac{a}{c} floor imes i + lfloor frac{b}{c} floor \ = & ; f(a',b',c,n) + frac{n(n+1)}{2} imes lfloor frac{a}{c} floor + (n+1) imes lfloor frac{b}{c} floor end{align*}$$
当 $a<c$ 且 $b<c$ 时,设 $m= lfloor frac{an+b}{c} floor$,有
$$egin{align*} f(a,b,c,n) = & sum_{i=0}^n ; lfloor frac{ai+b}{c} floor \ = & sum_{j=1}^m sum_{i=0}^n ; [ lfloor frac{ai+b}{c} floor geq j ] \ = & sum_{j=0}^{m-1} sum_{i=0}^n ; [ lfloor frac{ai+b}{c} floor geq j+1 ] \ = & sum_{j=0}^{m-1} sum_{i=0}^n ; [ ai geq jc+c-b ] \ = & sum_{j=0}^{m-1} sum_{i=0}^n ; [ ai > jc+c-b-1 ] \ = & sum_{j=0}^{m-1} sum_{i=0}^n ; [ i > lfloor frac{jc+c-b-1}{a} floor ] \ = & sum_{j=0}^{m-1} n- lfloor frac{jc+c-b-1}{a} floor \ = & ; nm - sum_{j=0}^{m-1} ; lfloor frac{jc+c-b-1}{a} floor \ = & ; nm-f(c,c-b-1,a,m-1) end{align*}$$
这与欧几里得算法通过取模缩小范围递归的思想相似,时间复杂度为 $O(log ; a)$
ll f(ll a, ll b, ll c, ll n) { if (!a) return b / c * (n + 1); if (a < c && b < c) { ll m = (a * n + b) / c; if (!m) return 0; return n * m - f(c, c - b - 1, a, m - 1); } if (n & 1) return f(a % c, b % c, c, n) + (n + 1) / 2 * n * (a / c) + (n + 1) * (b / c); return f(a % c, b % c, c, n) + n / 2 * (n + 1) * (a / c) + (n + 1) * (b / c); }