类欧几里得算法

  对于求和式 $f(a,b,c,n)=\sum_{i=0}^n \lfloor \frac{ai+b}{c} \rfloor$

  当 $a \geq c$ 或 $b \geq c$ 时,设 $a'=a \; mod \; c$,$b'=b \; mod \; c$,有

$$\begin{align*} f(a,b,c,n) = & \sum_{i=0}^n \; \lfloor \frac{ai+b}{c} \rfloor \\ = & \sum_{i=0}^n \; \lfloor \frac{a'i+b'}{c} \rfloor + \lfloor \frac{a}{c} \rfloor \times i + \lfloor \frac{b}{c} \rfloor \\ = & \; f(a',b',c,n) + \frac{n(n+1)}{2} \times \lfloor \frac{a}{c} \rfloor + (n+1) \times \lfloor \frac{b}{c} \rfloor \end{align*}$$

  当 $a<c$ 且 $b<c$ 时,设 $m= \lfloor \frac{an+b}{c} \rfloor$,有

$$\begin{align*} f(a,b,c,n) = & \sum_{i=0}^n \; \lfloor \frac{ai+b}{c} \rfloor \\ = & \sum_{j=1}^m \sum_{i=0}^n \; [ \lfloor \frac{ai+b}{c} \rfloor \geq j ] \\ = & \sum_{j=0}^{m-1} \sum_{i=0}^n \; [ \lfloor \frac{ai+b}{c} \rfloor \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} \rfloor ] \\ = & \sum_{j=0}^{m-1} n- \lfloor \frac{jc+c-b-1}{a} \rfloor \\ = & \; nm - \sum_{j=0}^{m-1} \; \lfloor \frac{jc+c-b-1}{a} \rfloor \\ = & \; nm-f(c,c-b-1,a,m-1) \end{align*}$$

上一篇:张逸解构DDD:软件的核心是为用户解决领域相关的问题(1)


下一篇:AC策略