类欧几里得算法
要求以下函数:
\[f(a, b, c, n) = \sum_{i = 0}^n \lfloor \frac{ai + b}{c} \rfloor
\]
设\(a = k_1 \times c + a', b = k_2 \times c + b'\),则
\[\lfloor \frac{ai + b}{c} \rfloor = \lfloor \frac{(k_1 \times c + a') \times i + (k_2 \times c + b')}{c} \rfloor = \lfloor \frac{a'i + b'}{c} \rfloor + k_1 \times i + k_2$$。
所以$$f(a, b, c, n) = f(a \bmod c, b \bmod c, c, n) + \frac{n(n + 1)}{2} \times \lfloor \frac{a}{c} \rfloor + (n + 1) \times \lfloor \frac{b}{c} \rfloor$$。
所以只需考虑$a < c$且$b < c$的情况。
令$m = \lfloor \frac{an + b}{c} \rfloor$,
$\sum\limits_{i = 0}^n \lfloor \frac{ai + b}{c} \rfloor$
$= \sum\limits_{i = 0}^n \sum\limits_{j = 1}^m [\lfloor \frac{ai + b}{c} \rfloor \ge j]$
$= \sum\limits_{i = 0}^n \sum\limits_{j = 0}^{m - 1} [\lfloor \frac{ai + b}{c} \rfloor \ge j + 1]$
$= \sum\limits_{i = 0}^n \sum\limits_{j = 0}^{m - 1} [ai \ge jc + c - b]$
$= \sum\limits_{i = 0}^n \sum\limits_{j = 0}^{m - 1} [ai > jc + c - b - 1]$
$= \sum\limits_{i = 0}^n \sum\limits_{j = 0}^{m - 1} [i > \frac{cj + c - b - 1}{a}]$
$= \sum\limits_{j = 0}^{m - 1} \sum\limits_{i = 0}^n [i > \frac{cj + c - b - 1}{a}]$
$= \sum\limits_{j = 0}^{m - 1} (n - \lfloor \frac{cj + c - b - 1}{a} \rfloor)$
$= nm - \sum\limits_{j = 0}^{m - 1} \lfloor \frac{cj + c - b - 1}{a} \rfloor$
$= nm - f(c, c - b - 1, a, m - 1)$
综上:
$$f(a, b, c, n) = \left \{ \begin{aligned} & {(n + 1) \times \lfloor \frac{b}{c} \rfloor} & a = 0 & \\ & {-f(c, c - b \bmod c - 1, a \bmod c, \lfloor \frac{(a \bmod c)n + b \bmod c}{c} \rfloor - 1) + n \times \lfloor \frac{(a \bmod c)n + b \bmod c}{c} \rfloor + \frac{n(n + 1)}{2} \times \lfloor \frac{a}{c} \rfloor + (n + 1) \times \lfloor \frac{b}{c} \rfloor} & a > 0 & \end{aligned} \right.\]
它把求\(f(a, b, c, n)\)转化为求\(f(c, b', a \bmod c, n')\),这和欧几里得算法很类似,这类算法称之为类欧几里得算法。
留坑......